1

I've faced with problem where I have to sort the XDocument by node name. Example

<contact>
    <email></email>
    <address></address>
    <name></name> 
</contact>

And I want to get

<contact>
    <address></address>
    <email></email>
    <name></name>
</contact>

Thank you for your help.

I've tried to use

var ab = xdoc.Descendants("contact");
            var s = from abs in ab
                    orderby abs.Name.ToString() descending
                    select abs;

but the result staying the same

1 Answers1

1

You need to replace the child nodes with the ordered nodes:

            XDocument doc = XDocument.Parse(@"<contact>
    <email></email>
    <address></address>
    <name></name> 
</contact>");
            doc.Root.ReplaceNodes(doc.Root.Elements().OrderBy(el => el.Name.LocalName));
Martin Honnen
  • 160,499
  • 6
  • 90
  • 110