序列化不带类名的 XML 列表元素

本文关键字:XML 列表元素 序列化 | 更新日期: 2023-09-27 17:56:26

I 以下类:

public class Family
{
    public List<ChildAge> childAges { get; set; }
}

现在,ChildAge 看起来像这样:

public class ChildAge
{
    public int Age { get; set; }
}

当我将其序列化为 XML 时,我得到:

<root>
    <Family>
        <ChildAges>
            <ChildAge>
                <Age>10</Age>
            </ChildAge>
            <ChildAge>
                <Age>8</Age>
            </ChildAge>
        </ChildAges>
    </Family>
</root>

我需要更改什么才能获得此内容:

<root>
    <Family>
        <ChildAges>
            <Age>10</Age>
            <Age>8</Age>
        </ChildAges>
    </Family>
<root>

谢谢!

序列化不带类名的 XML 列表元素

一旦您在"childage"下有更多属性要序列化,您的问题就会开始您可以简单地使用列表和以下注释:

[XmlArray("ChildAges")]
[XmlArrayItem("Age")]
List<int> ChildrenAges { get; set; }

你差不多完成了

您可以通过提供自己的 WriteXML 实现来做到这一点(以及更多)。

请看下面的代码段。

public class Family : IXmlSerializable
{
    public List<ChildAge> childAges { get; set; }
    public void WriteXml(XmlWriter writer)
    {
        foreach(ChildAge ca in childAges)
            writer.WriteElementString("Age", ca.Age.ToString());
    }
    public void ReadXml(XmlReader reader)
    {
        // [...]
    }
    public XmlSchema GetSchema()
    {
        return (null);
    }
}
public class ChildAge
{
    public int Age { get; set; }
}
public class Program
{
    static void Main(string[] args)
    {
        Family f = new Family();
        f.childAges = new List<ChildAge>();
        f.childAges.Add(new ChildAge() { Age = 10 });
        f.childAges.Add(new ChildAge() { Age = 8 });
        XmlSerializer xs = new XmlSerializer(typeof(Family));
        XmlSerializerNamespaces xmlnsEmpty;
        xmlnsEmpty = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
        XmlWriterSettings writerSettings = new XmlWriterSettings();
        writerSettings.Indent = true;
        writerSettings.OmitXmlDeclaration = true;
        StringBuilder sb = new StringBuilder();
        XmlWriter writer = XmlTextWriter.Create(sb, writerSettings);
        xs.Serialize(writer, f, xmlnsEmpty);
        Console.WriteLine(sb.ToString());
        Console.ReadLine();
    }
}