1

I want to be able to specify the order of the attributes.

Take the below code.

XmlDocument doc = new XmlDocument();
XmlElement element = doc.CreateElement("Test");
XmlElement subelement = doc.CreateElement("SubTest");
XmlAttribute att1 = doc.CreateAttribute("Value1");
XmlAttribute att2 = doc.CreateAttribute("Value2");     
subelement.Attributes.Append(att1);
subelement.Attributes.Append(att2);
element.AppendChild(subelement);
doc.AppendChild(element);
doc.Save("C:\\Test.xml");

Creates this:

<Test>
  <SubTest Value1="" Value2="" />
</Test>

Is there some way for me to dictate that Value2 is always first and Value1 is always second apart from the order they are added to the XmlDocument?

I know this doesnt matter when is comes to a valid XML document, but i would like to accomplish this for ease of reading by a human.

CathalMF
  • 9,705
  • 6
  • 70
  • 106
  • Please provide the details. 1. How are you differentiates the Value1 and Value2? 2. On What basis the Value2 should precede Value1? –  Jan 14 '19 at 18:01
  • Entity ordering is required in XML. Attribute ordering is not. There's a canonical XML standard that imposes an ordering, but XML doesn't need to be canonical to be valid. I believe that, unless you write all the bits and pieces out yourself (using an `XmlWriter`), you don't get any control over attribute ordering. Take a look at https://stackoverflow.com/questions/31195817/what-decides-the-order-of-xml-attributes-in-wcf-wsdl, https://stackoverflow.com/questions/726395/order-of-xml-attributes-after-dom-processing and http://www.w3.org/TR/xml-c14n11/ – Flydog57 Jan 14 '19 at 18:58

0 Answers0