37

我有一个类似于以下内容的 XML 文档:

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

我希望使用这些System.Xml.Serialization属性来简化 XML 反序列化。我遇到的问题是我无法弄清楚如何指定根节点包含一个数组。

我尝试创建以下类:

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

public class ScanDetail
{
    [XmlAttribute("name")]
    public string Filename { get; set; }
}

但是,当我将 XML 反序列化为ScanDetails对象时,Items数组仍然存在null

如何反序列化根节点中的数组?

4

1 回答 1

69

您应该使用[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);
        }
    }
}
于 2012-10-16T22:19:40.270 回答