用XPath排序 - 不是XSL

Wil*_*eth 4 c# xml xpath

在使用带有排序参数的System.Xml运行selectNodes(XPATH)的XPath DOM编程中有什么办法吗?

例如,使用以下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 );
        }
    }
Run Code Online (Sandbox Code Playgroud)

这是XML

<xml>
<ele value='3' test='Third'/>
<ele value='2' test='Second'/>
<ele value='1' test='First'/>
</xml>
Run Code Online (Sandbox Code Playgroud)

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

3
2
1
Run Code Online (Sandbox Code Playgroud)

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

Ale*_*kov 6

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

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

XmlDocument xml = new XmlDocument ();
xml.LoadXml("<xml> <ele value='3' test='Third'/> <ele value='2' test='Second'/> <ele value='1' test='First'/> </xml>");
var nodes = xml.SelectNodes( "/xml/ele" ).Cast<XmlNode>().OrderBy(ndNode => ndNode.Attributes["value"].Value);
Run Code Online (Sandbox Code Playgroud)


Woj*_*teq 5

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