C# – Including arrary index in XML Serialization

cnetxml-serialization

I have a class that looks like this

public class SomeClass
{
    public SomeChildClass[] childArray;
}

which will output XML from the XMLSerializer like this:

<SomeClass>
   <SomeChildClass>
      ...
   </SomeChildClass>
   <SomeChildClass>
      ...
   </SomeChildClass>
</SomeClass>

But I want the XML to look like this:

<SomeClass>
   <SomeChildClass index=1>
      ...
   </SomeChildClass>
   <SomeChildClass index=2>
      ...
   </SomeChildClass>
</SomeClass>

Where the index attribute is equal to the items position in the array.

I could add an index property to SomeChildClass with the "XMLAttribute" attribute but then I would have to remember to loop through the array and set that value before I serialize my object.

Is there some attribute i can add or some other way to automatically generate the index attribute for me?

Best Answer

The best approach would be to do what you said and add a property to the "SomeChildClass" like this

[XmlAttribute("Index")]
public int Order
{  { get; set; }   }

Then however you are adding these items to your array, make sure that this property get's set. Then when you serialize....Presto!