views:

385

answers:

2

I have a 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.

+7  A: 

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));
ArsenMkrt
I do that but i have an exception. "At least one object must implement IComparable".
cagin
it needs to be `node.Attribute("Name").Value`
Daniel Schaffer
FYI, doing a stright `node.Attribute("Name").Value` leaves you open for a null reference exception if that attribute is missing. Also, if the XML document specifies a schema, just doing `node.Attribute("Name")` won't be enough either, as you'll have to use a proper `XName` to find the attribute.
Daniel Schaffer
A: 
        XDocument xdoc = new XDocument(
            new XElement("Users",
                new XElement("Name", "Z"),
                new XElement("Name", "D"),
                new XElement("Name", "A")));

        var doc = xdoc.Element("Users").Elements("Name").OrderBy(n => n.Value);
        XDocument doc2 = new XDocument(new XElement("Users", doc));
RandomNoob
Name is an attribute, not an element ;)
Daniel Schaffer
@Daniel : oh crap! Oh well, my bad. OP can correct
RandomNoob