用XPath排序 – 不是XSL

XPath DOM编程中是否有任何方法使用System.Xml来运行带有排序参数的selectNodes (XPATH)?

例如,使用以下XML和程序以与文档相同的顺序写入值(降序)。 有没有办法使用XPath以升序获取值?

注意。 当然,您可以在XSL中进行预排序,但是我需要更新值,因为我正在循环它们。 由于XSL给了我一个元素的排序副本而不是实际的元素本身 ,我不能使用XSL。

这是一些XML,一个程序输出

 public static void Main() { XmlDocument xml = new XmlDocument(); xml.Load( "t.xml" ); // SelectNodes gets in document order, but I want in // ascending order based on @value foreach( XmlNode ndNode in xml.SelectNodes( "/xml/ele" ) ) { Console.WriteLine( ndNode.Attributes["value"].Value ); } } 

这是XML

      

最后输出文件(降序)顺序。 我想要一个以升序返回节点的XPath。

 3 2 1 

PS,我在Visual Studio 2008 .NET 3.5中使用System.Xml

XPath不支持排序,但是您可以查看AddSort方法。

不,没有办法单独在XPath中进行排序。

但是,您可以轻松地使用LINQ按您想要的任何值对节点集合进行排序。

 XmlDocument xml = new XmlDocument (); xml.LoadXml("    "); var nodes = xml.SelectNodes( "/xml/ele" ).Cast().OrderBy(ndNode => ndNode.Attributes["value"].Value);