List<Int> XML serialization

c#, xml

Solution

You can use XmlArray and XMLArrayItem attribute together to top of your variable declaration. Then XmlSerializer consider these attributes when start to serializing defined object. Let me give you an example with your code;

You should define your generic list with these attributes.

public class democlass
{

    [XmlArray("testList")]
    [XmlArrayItem("customitem")]
    public List<int> testList {get;set;}
}

Then, You can add values to your list

    static void Main(string[] args)
    {
        democlass d = new democlass();
        d.testList = new List<int>();
        d.testList.Add(1);
        d.testList.Add(2);
        d.testList.Add(3);

And serialize it. You will be see this output.

<democlass>
    <testList>
        <customitem>1</customitem>
        <customitem>2</customitem>
        <customitem>3</customitem>
    </testList>
</democlass>

Thats it.

I hope this will be help.

Note : The magic is inisde of the `XmlArray` and `XmlArrayItem` attributes, you can find more detailed information on MSDN.

Regards

Problem

``` List<int> testList = new List<int>(); testList.Add(1); testList.Add(2); testList.Add(3); XmlSerializer xs = new XmlSerializer(typeof(List<int>)); ``` This code (partial) creates a default root node `<ArrayOfInts>` and every node: `<int>`. Is it possible to set differet names, without creating wrapping class? Thanks

Original source