使用多个值反序列化XML

时间:2014-11-24 16:50:30

标签: c# xml serialization

我使用此Xml Deserialization with complex elements in c#作为参考。我注意到有很多关于反序列化xml的主题,但是当标签中有多个值时,他们不会提及。

我正在尝试将我的xml for lvl3反序列化为一个对象数组。

我得到一个" xml文档中存在错误(1,2)"错误。

我有一个xml字符串,我通过HTTP GET请求检索,格式如下:

<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>

我有以下代码不断抛出异常:

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

此行抛出异常:

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

但我不确定如何调试它以找到错误。这是完整的代码:

    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; }
    }

1 个答案:

答案 0 :(得分:0)

修复Test类以包含val1val2属性的公共属性,或从xml中删除它们。 xml的模式应该与类结构匹配。