Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting Attributes of Xml

Tags:

c#

xml

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.

like image 720
SMD Avatar asked Oct 22 '11 16:10

SMD


1 Answers

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>
like image 75
Muhammad Hasan Khan Avatar answered Oct 05 '22 18:10

Muhammad Hasan Khan