Xml attribute sorting

My input is the same as the purged Xml:

<Phrase Entry="ID"> <Ans number="1"> <Identification LastName="Bornery" Name="John" Age="23"/> </Ans> </Phrase> 

and I want to sort the Xml attribute base in their first order of character names into alphabetical arrangements, for example, deflated Xml:

 <Phrase Entry="ID"> <Ans number="1"> <Identification Age="23" LastName="Bornery" Name="John" /> </Ans> </Phrase> 

thanks.

+7
source share
2 answers

Your xml output file is incorrect, but if the input was like this:

 <Phrase Entry="ID"> <Ans number="1"> <Blah LastName="Bornery" Name="John" Age="23"/> </Ans> </Phrase> 

Then the following code

 static string SortAttributes(string xml) { var doc = XDocument.Parse(xml); foreach (XElement element in doc.Descendants()) { var attrs = element.Attributes().ToList(); attrs.Remove(); attrs.Sort((a, b) => a.Name.LocalName.CompareTo(b.Name.LocalName)); element.Add(attrs); } xml = doc.ToString(); return xml; } 

Will return it

 <Phrase Entry="ID"> <Ans number="1"> <Blah Age="23" LastName="Bornery" Name="John" /> </Ans> </Phrase> 
+9
source

If you want to compare two XML documents as strings, you must convert them to Canonical XML. This involves much more than getting attributes in canonical order: it involves, for example, normalizing spaces and possibly namespace prefixes. Find the XML canonicalization utility.

0
source

All Articles