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

I am currently using XmlSerializer to serialize and deserialize an object. Xml is generated in undefined order, which is understandable, but makes it annoying when comparing versions of an object, since the order of the properties is different every time. So, for example, I cannot use the usual 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 themselves? I have many properties in the class and every time I add new ones, so I prefer not to write or support this code.

(C # .net 2.0)

+6
c # xml xml-serialization
source share
3 answers

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

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

+9
source share

Decorate your properties with XmlElementAttribute by setting Order .

+2
source share

ps: I do not believe that the XML generated by the XmlSerializer is in undefined order. This may be undocumented, but known. I believe that in the absence of the Order attributes, the XmlSerializer serializes all public properties, alpha sort by name prop, and then all public fields sorted by name alphabetically.

0
source share

All Articles