Rory
Rory

Reputation: 41897

Any way to make XmlSerializer output xml in a defined order?

Currently I'm using XmlSerializer to serialize and deserialize an object. The xml is generated in an undefined order which is understandable but makes it annoying when comparing versions of the object, since the order of properties is different each time. So for instance I can't use a normal diff tool to see any differences.

Is there an easy way to generate my xml in the same order every time, without writing the ReadXml and WriteXml methods myself? I have a lot of properties on the class, and add new ones every now and again, so would prefer to not have to write and then maintain that code.

(C# .net 2.0)

Upvotes: 7

Views: 6085

Answers (3)

Cheeso
Cheeso

Reputation: 192621

ps: I don't believe the XML generated by the XmlSerializer is in an undefined order. It may be undocumented, but it is known. I believe that in the absence of Order attributes, the XmlSerializer serializes all public Properties, alpha-sorted by prop name, and then all public Fields, alpha-sorted by name.

Upvotes: 0

bdukes
bdukes

Reputation: 156045

Decorate your properties with the XmlElementAttribute, setting the Order parameter.

Upvotes: 2

Szymon Rozga
Szymon Rozga

Reputation: 18178

The XmlElement attribute has an order property. You can use that as a start.

If you need to find the diff in Xml files, you might want to take a look at this.

Upvotes: 10

Related Questions