C# 将 XmlSerializer 与根元素中的数组一起使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12924221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 00:58:20  来源:igfitidea点击:

Using XmlSerializer with an array in the root element

c#.netarraysxml-serialization

提问by Hand-E-Food

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.Serializationattributes to simplify XML deserialization. The issue I have is I cannot work out how to specify that the root node contains an array.

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

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 ScanDetailsobject the Itemsarray remains null.

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

How do I deserialize an array in a root node?

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

采纳答案by carlosfigueira

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