I'm using an XmlSerializer to serialize an object and write it to a file. I've had quite a bit of success with the serializer doing what I want it to do in terms of nesting elements and what is serialized as elements vs attributes. Unfortunately, I've run into a problem where I need one member of a class to serialize before another. Elsewhere it's worked for me that whatever is declared first gets serialized first, but in this instance I'm not having so much success with that. Is there any way to manually control the order in which things are serialized?
Asked
Active
Viewed 1.7k times
2 Answers
33
[XmlElementAttribute(Order = 1)]
public int Field1 {...}
[XmlElementAttribute(Order = 2)]
public int Field2 {...}
Catch: You must specify the Order
for all of your members.
Be careful - deserialization will only work if the properties in the XML document are in the same order. Otherwise it will silently ignore out-of-order properties.

Cyanfish
- 3,907
- 1
- 14
- 12

Robert Harvey
- 178,213
- 47
- 333
- 501
-
Perfect. I guess I either missed that on MSDN or didn't dig enough to find it. Thanks. – Zann Anderson Jul 30 '10 at 20:43
-
Possibly related: Is there any way to control the order with XML attributes? `XmlAttributeAttribute` does not have such a property. – Travis Gockel Aug 05 '10 at 01:41
-
1@Travis: In my experience, there are fewer (if any) problems with getting attributes to serialize in the order they are declared. – Robert Harvey Aug 05 '10 at 02:01
-
if you don't specify order for all does it add the rest at the end or at the start? Would be nice to allow negative numbers to control that – George Birbilis Nov 11 '20 at 09:00
-
to answer my own comment, unfortunately XmlSerializer requires you to add order for all elements and to have such at ancestor classes too. If you can't control ancestor class, can use XmlAttributeOverride as I show here: https://dotnetfiddle.net/Bvbi0N – George Birbilis Nov 17 '20 at 12:25
3
XmlElementAttribute.Order
, which controls "the explicit order in which the elements are serialized or deserialized".

Tim Robinson
- 53,480
- 10
- 121
- 138