C#中的XmlSerialization-根元素数组

本文关键字:元素 数组 XmlSerialization- 中的 | 更新日期: 2023-09-27 18:00:37

我想对type=array作为根节点的XML文档进行反序列化。给定的xml结构如下所示:

<?xml version="1.0" encoding="UTF-8"?>
    <parties type="array">
        <party type="Person">
            <id>1</id>
            <lastname>Smith</lastname>
            <firstname>Peter</firstname>
            ...
        </party>
        <party type="Person">
            <id>2</id>
            <lastname>Smith</lastname>
            <firstname>Sarah</firstname>
            ...
        </party>
    <parties type="array">

C#代码如下:

[XmlRootAttribute("parties", Namespace = "", IsNullable = false)]       
public class Parties
{
    private ArrayList contacts = new ArrayList();

    public Parties()
    {
    }

    [XmlArray("parties"), XmlArrayItem("party", typeof(Person))]
    public ArrayList Contacts
    {
        get { return contacts; }
        set { contacts = value; }
    }
}

结果xml输出如下:

<?xml version="1.0" encoding="utf-8"?>
    <parties xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xmlns:xsd="http://www.w3.org/2001/XMLSchema">
        <parties>
            <party>
                <id>0</id>
                <lastname>Smith</last-name>
                <firstname>Peter</first-name>
            </party>
        </parties>
    </parties>

问题是我现在有两个标签。如何指定根元素的数组类型?有什么想法可以在不更改给定xml模式的情况下修复它吗?

C#中的XmlSerialization-根元素数组

试试这个:

[XmlElement("party")]
public ArrayList Contacts
{
    get { return contacts; }
    set { contacts = value; }
}