Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sort an XDocument by attribute?

I have some XML

<Users>
    <User Name="Z"/>
    <User Name="D"/>
    <User Name="A"/>
</User>

I want to sort that by Name. I load that xml using XDocument. How can I view that xml sorted by Name?

like image 727
cagin Avatar asked Feb 09 '10 19:02

cagin


1 Answers

You can sort using LINQ to Xml, if XmlDocument is not the case

XDocument input = XDocument.Load(@"input.xml");
XDocument output = new XDocument(
    new XElement("Users",
        from node in input.Root.Elements()
        orderby node.Attribute("Name").Value descending
        select node));
like image 106
Arsen Mkrtchyan Avatar answered Sep 25 '22 07:09

Arsen Mkrtchyan