c# - 重新排序 XML 节点

标签 c# linq-to-xml

我有一些看起来像这样的 XML:

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

这不是我拥有的实际数据,但它可以满足这里的目的。我想要做的是使用 Linq to SQL 对 XML 重新排序,以便子节点按字母顺序排列,例如。

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

然后我希望能够在原始 XDocument 上调用 ToString() 并让它返回第二组 XML,如上所示。有没有简单的方法可以做到这一点?我试过搜索,但运气不好。

最佳答案

也许:

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

或者稍微灵活一点(尽管只支持 1 层嵌套):

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

关于c# - 重新排序 XML 节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6333241/

相关文章:

c# - 正则表达式问题匹配字符串模式“A-Za-z-A-Za-z_”

c# - 需要有关在 .NET 4 中解析 XML 的信息

c# - 使用 xmlns 属性( namespace )查询 XDocument

c# - X文档 : is it possible to force the load of a malformed XML file?

c# - 为什么这个字符串属性在不应该被覆盖的情况下显示为被完全覆盖?

c# - 由于编码问题,在 iOS 上从 C# 调用 DLL 库时出现问题

c# - UWP SQL 连接错误 [c#]

c# - 为什么我可以创建一个名为 "var"的类?

c# - 打开一个excel文件并添加单元格值

c# - XDocument 在一行中写入特定的 XElement