ATL_DEV
ATL_DEV

Reputation: 9591

How do I get XmlSerializer to not serialize list container tags?

I have a simple object graph that I would like to serialize, I haven't been able to find a solution to this problem. Here it is:

   [XmlRoot]
    public partial class MyData
    {

        private List<MyDatum> itemsField;

        public MyData()
        {
            this.anyAttrField = new List<System.Xml.XmlAttribute>();
            this.itemsField = new List<MyDatum>();
        }

        [XmlElement(Type = typeof(MyDatum))]
        public List<MyDatum> Items
        {
            get
            {
                return this.itemsField;
            }
            set
            {
                this.itemsField = value;
            }
        }
    }

This produces the following XML:

<MyData>
    <Items>
        <MyDatum/>
        <MyDatum/>
        ...
    </items>
</MyData>

I would like to remove the "Items" container tag to produce this instead:

<MyData>
    <MyDatum/>
    <MyDatum/>
    ...
</MyData>

I've tried all kinds of solutions, but can't seem to find a solution.

Upvotes: 17

Views: 9867

Answers (1)

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 262989

Specify an element name in your [XmlElement] attribute:

[XmlElement("MyDatum", Type = typeof(MyDatum))]
public List<MyDatum> Items {
    // ...
}

According to this article on MSDN, this will remove the wrapper element around serialized items.

Upvotes: 28

Related Questions