views:

198

answers:

3

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?

A: 

You may need to look into implementing System.Xml.Serialization.IXmlSerializable to accomplish this.

Craig Eddy
A: 

You can check XmlAttributeOverrides Class.

Sunny
+1  A: 

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!

Micah
I wish there was a better solution but this is simple and works.
TonyB
small correction : [XmlAttribute("index")] ("index" instead of "Item")
Andrei Rinea
hehe..nice catch. Made the change!
Micah
How would you deserialize this to enforce this to enforce the order?
Joel Coehoorn