0

I was using this Xml Deserialization with complex elements in c# as a reference. I've noticed there are a lot of threads about Deserializing xml, but they don't mention when a tag has multiple values within it.

I am trying to deserialize my xml for lvl3 into an array of objects.

I'm getting a "there is an error in the xml document (1, 2)" error.

I have an xml string that I'm retrieving via an HTTP GET request that is formatted like this:

<xml ...>
   <lvl1 id="xxx" name="yyy">
      <lvl2 id="aaa" name="bbb">
         <lvl3 id="mmm" name="nnn" val1="ppp" val2="qqq">
            <lvl4a x="000" y="000" z="000" />            
            <lvl4b a="000" b="000" c="000" />
            <lvl4c l="000" w="000" h="000" />
            ...
         </lvl3>
      </lvl2>
   </lvl1>
</xml>

I have the following code that keeps throwing an exception:

"An unhandled exception of type 'System.InvalidOperationException' occurred in System.Xml.dll"

The exception is thrown by this line:

temp = (Test)new XmlSerializer(typeof(Test)).Deserialize(rdr);

But I'm not sure how to go about debugging it to find the error. Here is the complete code:

    XmlDocument xmldoc = new XmlDocument();
    xmldoc.LoadXml(xmlstring);

    XmlNodeList list = xmldoc.GetElementsByTagName("lvl2");
    for (int i = 0; i < list.Count; i++)
    {
        Test temp = new Test();
        using (XmlReader rdr = XmlReader.Create(new StringReader(list[i].InnerXml)))
        {
            temp = (Test)new XmlSerializer(typeof(Test)).Deserialize(rdr); // exception thrown here
        }
        Console.WriteLine(temp.id);
        Console.WriteLine(temp.overall.x);
    }

    [XmlRoot("lvl3")]
    public class Test{
        [XmlAttribute("id")]
        public string id { get; set; }

        [XmlAttribute("name")]
        public string name { get; set; }

        [XmlElement(ElementName = "lvl4a")]
        public Overall overall { get;set; }
    }

    public class Overall
    {
        [XmlAttribute("x")]
        public string x { get; set; }

        [XmlAttribute("y")]
        public string y { get;set; }

        [XmlAttribute("z")]
        public string z { get;set; }
    }
Community
  • 1
  • 1
Kmat
  • 401
  • 1
  • 6
  • 14

1 Answers1

0

Either fix your Test class to include public properties for val1 and val2 attributes or remove them from the xml. The schema of xml should match the class structure.

Piyush Parashar
  • 866
  • 8
  • 20