简体   繁体   中英

Serialize List Elements in XML without class name

I the following class:

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

Now the ChildAge looks like this:

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

When I serialize this to XML I get:

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

What do I need to change to get this:

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

Thanks!

You can do it (and much more) by providing your own implementation of WriteXml...

Please take a look at the following piece of code.

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

Your problem will begin once you'll have more properties to serialize under "childage" you could simply use a list and the following annotations:

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

and you're pretty much done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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