簡體   English   中英

使用多個值反序列化XML

[英]Deserialize XML with multiple values

在C#中使用帶有復雜元素的Xml反序列化作為參考。 我注意到有很多關於反序列化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; }
    }

修復Test類以包含val1val2屬性的公共屬性,或者從xml中刪除它們。 xml的模式應與類結構匹配。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM