Using XmlSerializer with an array in the root element

匿名 (未验证) 提交于 2019-12-03 01:57:01

问题:

I have an XML document similar to the following:

         ...                   ...          ... 

I am hoping to use the System.Xml.Serialization attributes to simplify XML deserialization. The issue I have is I cannot work out how to specify that the root node contains an array.

I have tried creating the following classes:

[XmlRoot("scan_details")] public class ScanDetails {     [XmlArray("object")]     public ScanDetail[] Items { get; set; } }  public class ScanDetail {     [XmlAttribute("name")]     public string Filename { get; set; } } 

However when I deserialize the XML into the ScanDetails object the Items array remains null.

How do I deserialize an array in a root node?

回答1:

You should use [XmlElement], and not [XmlArray] to decorate the Items property - it's already an array, and you only want to set the element name.

public class StackOverflow_12924221 {     [XmlRoot("scan_details")]     public class ScanDetails     {         [XmlElement("object")]         public ScanDetail[] Items { get; set; }     }      public class ScanDetail     {         [XmlAttribute("name")]         public string Filename { get; set; }     }      const string XML = @"                                                                                                                     ";      public static void Test()     {         XmlSerializer xs = new XmlSerializer(typeof(ScanDetails));         MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(XML));         var obj = xs.Deserialize(ms) as ScanDetails;         foreach (var sd in obj.Items)         {             Console.WriteLine(sd.Filename);         }     } } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!