重新排序XML节点 [英] Reorder XML nodes
本文介绍了重新排序XML节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些看起来像这样的XML:
I’ve got some XML that looks something like this:
<root>
<item>Banana</item>
<item>Apple</item>
<item>Cherry</item>
</root>
这不是我的实际数据,但在这里可以达到目的.我想做的是使用Linq to SQL对XML重新排序,以便子节点按字母顺序排列,例如.
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>
我希望能够在原始XDocument上调用ToString()
,并使其返回第二组XML,如上所示.有没有简单的方法可以做到这一点?我尝试搜索,但没有运气.
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.
推荐答案
也许:
var reordered = new XElement(
"root",
xdoc.Root.Elements("item")
.OrderBy(x => x.Value)
.Select(x => new XElement("item", x.Value)));
或者稍微灵活一些(尽管仅支持1个嵌套级别):
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)));
这篇关于重新排序XML节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文