Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 863
ATL_DEV Avatar asked Nov 20 '11 05:11

ATL_DEV


People also ask

Can I make XmlSerializer ignore the namespace on Deserialization?

Yes, you can tell the XmlSerializer to ignore namespaces during de-serialization.

How can you modify control the XML that is being generated by XmlSerializer?

By applying the XmlRootAttribute, you can control the XML stream generated by the XmlSerializer. For example, you can change the element name and namespace. The XmlTypeAttribute allows you to control the schema of the generated XML.

What does it mean to serialize XML?

XML serialization is the process of converting XML data from its representation in the XQuery and XPath data model, which is the hierarchical format it has in a Db2® database, to the serialized string format that it has in an application.

Is XmlSerializer thread safe?

Since XmlSerializer is one of the few thread safe classes in the framework you really only need a single instance of each serializer even in a multithreaded application. The only thing left for you to do, is to devise a way to always retrieve the same instance.


1 Answers

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.

like image 106
Frédéric Hamidi Avatar answered Oct 11 '22 18:10

Frédéric Hamidi