My input is as a such as the blew Xml:
<Phrase Entry="ID">
<Ans number="1">
<Identification LastName="Bornery" Name="John" Age="23"/>
</Ans>
</Phrase>
and I want to sort the Xml attributes base on their first character Names order by alphabetic arrangment such as the blew Xml:
<Phrase Entry="ID">
<Ans number="1">
<Identification Age="23" LastName="Bornery" Name="John" />
</Ans>
</Phrase>
thanks.
Your output xml is wrong but if input was like so:
<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 this
<Phrase Entry="ID">
<Ans number="1">
<Blah Age="23" LastName="Bornery" Name="John" />
</Ans>
</Phrase>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With