Let me start off by saying I've seen the following questions:
- Controlling order of serialization in C#: It is about element order
- How to specify the order of XmlAttributes, using XmlSerializer: The answer just says "You don't"
- net xmlserializer : keeping attributes order: Again says "you don't" or the alternate answer states that you can but you have to do all of the serialisation yourself
I've also seen people state that the order that you specify the attributes in the class is the order that they will be serialised. However, in my case I have a base class that has attributes too so this doesn't seem to work out.
I have the following two classes:
public class MyClass : BaseClass
{
[XmlAttribute()]
public string Value1 { get; set; }
public MyClass()
: base()
{
Value1 = string.Empty;
}
}
public class BaseClass
{
[XmlAttribute()]
public string Value2 { get; set; }
[XmlAttribute()]
public string Value3 { get; set; }
public BaseClass()
{
Value2 = string.Empty;
Value3 = string.Empty;
}
}
When serialised to an XML element's attributes they appear in the order, Value2, Value3, Value1
. I'd like them to appear in the order Value1, Value2, Value3
.
I use the following method to save the XML to disk:
public static void Save<T>(string path, T contents)
{
using (StreamWriter sw = new StreamWriter(File.OpenWrite(path)))
{
XmlSerializer xml = new XmlSerializer(typeof(T));
xml.Serialize(sw, contents, ns);
}
}
Is there any way I can specify the attribute order? Like with elements:
[XmlElementAttribute(Order = 1)]
To those who will say something like "Order doesn't matter" or "If it works why do you need to change the order" or "XML isn't meant to be readable". My answer is yes the order doesn't matter and it works. However, when I'm debugging my code and checking the XML to make sure it contains the values I expect, it is a lot easier to read if the attributes are in the order I want them to be in.