I'm reading a document such as the following using XDocument:
<form>
<hiddencontrols>
<data classid="{5546E6CD-394C-4bee-94A8-4425E17EF6C6}" datafieldname="opportunityid" id="opportunityid"/>
<data classid="{5546E6CD-394C-4bee-94A8-4425E17EF6C6}" datafieldname="producttypecode" id="producttypecode"/>
</hiddencontrols>
</form>
Example load:
XmlReader rdr = XmlReader.Create(new System.IO.StringReader(xmlString));
XDocument xdoc = XDocument.Load(rdr, LoadOptions.None);
foreach (XElement xe in xdoc.Root.DescendantsAndSelf()) {
if (xe.NodeType == XmlNodeType.Element) {
if (xe.HasAttributes) {
foreach (XAttribute xa in xe.Attributes()) {
Within the foreach to iterate the attributes, the original order of the attributes in the original XML is NOT preserved. That is to say, when I write out the attributes again from within the foreach, they are written out in a different order from the original XML.
Example output (of just the first data node):
<data id="new_opportunityid" datafieldname="opportunityid" classid="{5546E6CD-394C-4bee-94A8-4425E17EF6C6}"/>
I have tried to determine if there is some consistency applied (eg. whether the XElement
parser always runs in reverse order or similar), there is no discernable pattern to the attribute order. I have also tried using just an XmlReader
without loading into an XDocument
, I have tried loading the XDocument
from a MemoryStream
instead of from the XmlReader
. All approaches yield the same result.
I am aware that within the XML specification attribute order is not significant, this is important to me because I am doing attribute value transformation within the foreach, and I want to be able to diff the final document against the original without having to account for different ordering of the attributes, but just seeing changes in values. It also matters for diff size within source control.