简体   繁体   English

在根元素中使用XmlSerializer和数组

[英]Using XmlSerializer with an array in the root element

I have an XML document similar to the following: 我有一个类似于以下的XML文档:

<scan_details>
    <object name="C:\Users\MyUser\Documents\Target1.doc">
        ...
    </object>
    <object name="C:\Users\MyUser\Documents\Target2.doc">
        ...
    </object>
    ...
</scan_details>

I am hoping to use the System.Xml.Serialization attributes to simplify XML deserialization. 我希望使用System.Xml.Serialization属性来简化XML反序列化。 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 . 但是,当我将XML反序列化为ScanDetails对象时, Items数组保持为null

How do I deserialize an array in a root node? 如何反序列化根节点中的数组?

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. 你应该使用[XmlElement] ,而不是[XmlArray]来装饰Items属性 - 它已经是一个数组,你只想设置元素名称。

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 = @"<scan_details> 
                            <object name=""C:\Users\MyUser\Documents\Target1.doc""> 
                            </object> 
                            <object name=""C:\Users\MyUser\Documents\Target2.doc""> 
                            </object> 
                        </scan_details> ";

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM