Reorder XML nodes

2019-05-26 09:28发布

问题:

I’ve got some XML that looks something like this:

<root>
    <item>Banana</item>
    <item>Apple</item>
    <item>Cherry</item>
</root>

It’s not the actual data I have, but it’ll serve the purpose here. What I want to do is use Linq to SQL to reorder the XML so that the child nodes are in alphabetical order, eg.

<root>
    <item>Apple</item>
    <item>Banana</item>
    <item>Cherry</item>
</root>

I want to be able to then call ToString() on the original XDocument and have it return the second set of XML as shown above. Is there a simple way of doing this? I’ve tried searching, but no such luck.

回答1:

Perhaps:

var reordered = new XElement(
                    "root",
                    xdoc.Root.Elements("item")
                             .OrderBy(x => x.Value)
                             .Select(x => new XElement("item", x.Value)));

Or the slightly more flexible (albeit only supporting 1 nested level):

var reordered = new XElement(
                    xdoc.Root.Name,
                    xdoc.Root.Elements()
                             .OrderBy(x => x.Value)
                             .Select(x => new XElement(x.Name, x.Value)));