c# – 根据属性订购XmlNodeList

我有一个XmlNodeList包含来自下面的
XML示例的根的数据包(项).我想根据节点的键属性值对XmlNodeList进行排序.

排序必须非常高效,每毫秒都很重要.

你有什么主意吗?

<root>
    <item key="1000000020">
        Content 20
    </item>
    <item key="1000000001">
        Content 1
    </item>
    ...
    <item key="1043245231">
        Content n
    </item>
</root>

编辑:
我已经从项目构造了一个XmlNodeList.我不再能够访问XmlDocument,只能访问项目列表.

最佳答案 您应该尝试使用Linq to XML.

 XDocument doc = XDocument.Load(file);

   var nodeList = from ele in doc.Descendants("item")
                   orderby int.Parse(ele.Attribute("key").Value)
                   select ele;

您可以尝试XPathNavigator和XPathExpression.

 //I presume that variable xNodeList contains XmlNodeList.
  XPathNavigator nav=xNodeList.Item(0).OwnerDocument.CreateNavigator();
  XPathExpression exp = nav.Compile("root/item");


  exp.AddSort("@key", XmlSortOrder.Ascending, XmlCaseOrder.None, "", XmlDataType.Number );

  foreach (XPathNavigator t in nav.Select(exp))
  {
    Console.WriteLine(t.OuterXml );
   }
点赞