0

I have a simple XML file with an array of objects:

<?xml version="1.0" encoding="UTF-8"?>
<complexes>
    <complex>
        <name>NAME1</name>
    </complex>
</complexes>

So I've made a class structure to suit it:

public complex[] complexes;

public class complex
{
    public string name;
}

And I do parsing with the standard C# tools:

XmlSerializer reader = new XmlSerializer(typeof(complex[]));
StreamReader file = new StreamReader("test.xml");
complexes = (complex[])reader.Deserialize(file);

For some reason I get an exception on the last line:

System.InvalidOperationException: 'There is an error in XML document (2, 2).'
InvalidOperationException: <complexes xmlns=''> was not expected.

What's the issue?

JustLogin
  • 1,822
  • 5
  • 28
  • 50
  • check this https://stackoverflow.com/questions/1556874/user-xmlns-was-not-expected-deserializing-twitter-xml – iSR5 Jul 16 '22 at 16:59
  • @iSR5 I have no issues parsing an object (which is an issue for the post you've mentioned). I only get an error while going with the array. – JustLogin Jul 16 '22 at 17:06
  • 1
    sorry, I've provided the wrong one, as the correct one is inside a comment in the same post. Here is the correct link : https://stackoverflow.com/questions/12672512/xmlns-was-not-expected-there-is-an-error-in-xml-document-2-2/59142448#59142448 – iSR5 Jul 16 '22 at 17:10

1 Answers1

0

Following works :

using System;
using System.Linq;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;


namespace ConsoleApp2
{
    class Program
    {

        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(complexes));
            XmlReader reader = XmlReader.Create(FILENAME);
            complexes complexes = (complexes)serializer.Deserialize(reader);

        }

    }
    public class complexes
    {
        [XmlElement("complex")]
        public complex[] complex { get; set; }
    }
    public class complex
    {
        public string name { get; set; }
    }


}
jdweng
  • 33,250
  • 2
  • 15
  • 20