c# - 如何在 C# 中对 XmlDocument 中的元素的子元素进行排序?

标签 c# xml linq xml-parsing xmldocument

我有一个 System.Xml.XmlDocument 类型的 XML 文档,如下所示:

<root>

  <group>
    <dog order="1" />
    <cat order="4" />
    <cat order="3" />
    <dog order="7" />
    <dog order="5" />
    <cat order="6" />
    <dog order="2" />
  </group>

  <other/>

</root>

我希望它是这样的

<root>

  <group>
    <dog order="1" />
    <dog order="2" />
    <cat order="3" />
    <cat order="4" />
    <dog order="5" />
    <cat order="6" />
    <dog order="7" />
  </group>

  <other/>

</root>

我在网上尝试了各种代码,但没有一个对我有用。我还将我的 XmlDocument 转换为 XDocument 以使用 LINQ,如下所示:

var xDoc = XDocument.Parse(xdoc.OuterXml);

还是没有成功

我需要对组元素 XmlDocument 中的子元素进行排序

最佳答案

一种选择是删除元素并在排序后再次添加它们。

XDocument doc  = XDocument.Load(filename);
var elements = doc.Root.Element("group").Elements().ToList();  // Copy the elements.

doc.Root.Element("group").RemoveAll();                         // Remove the elements from the document.
doc.Root.Element("group").Add(elements.OrderBy(x=>int.Parse(x.Attribute("order").Value)));
//Add them again after sorting.

检查这个Demo

输出

 <root>
  <group>
    <dog order="1" />
    <dog order="2" />
    <cat order="3" />
    <cat order="4" />
    <dog order="5" />
    <cat order="6" />
    <dog order="7" />
  </group>
</root>

关于c# - 如何在 C# 中对 XmlDocument 中的元素的子元素进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37480322/

相关文章:

c# - Entity Framework 正在执行太多查询

Android:如何通过xml制作一个看起来像光环的Circle

xml - Android Studio 中每行一个 XML 属性

linq - RavenDB,LINQ,从字符串 [] 中选择,其中数组不包含给定的字符串

c# - 从文本文件填充数据表

c# - 是否可以检测是否有使用 C# 连接的 HDMI 设备?

c++ - 从 stringstream boost read_xml 不读取 xml 格式

linq - 为什么linq join是单向的?

c# - 无法将类型 'System.Collections.Generic.IEnumerable<AnonymousType#1>' 隐式转换为 'System.Collections.Generic.List<modelClass>

c# - 将 XML 绑定(bind)到组合框