【问题标题】:Deserialize XML with multiple values使用多个值反序列化 XML
【发布时间】:2015-01-22 11:07:37
【问题描述】:

我使用这个Xml Deserialization with complex elements in c# 作为参考。我注意到有很多关于反序列化 xml 的线程,但是他们没有提到标签中何时有多个值。

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

我收到“xml 文档 (1, 2) 中有错误”错误。

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

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

【问题讨论】:

  • 您是否调试并检查异常发生在哪里以及是否存在内部异常?
  • 我做了,没有内部异常
  • 我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。

标签: c# xml serialization


【解决方案1】:

要么修复您的 Test 类以包含 val1val2 属性的公共属性,要么将它们从 xml 中删除。 xml 的 schema 应该与类结构相匹配。

【讨论】:

    猜你喜欢
    • 2011-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多