Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort with XPath - Not XSL

Tags:

c#

xml

xpath

Is there any way in XPath DOM Programming with using System.Xml to run selectNodes (XPATH) with a sort parameter?

For example, with the following XML and program writes values in the same order as the document (descending). Is there a way using XPath to get the values in ascending order?

NOTE. Of course, you could pre-sort in XSL, however I need to update the values as I'm looping through them. Since XSL gives me a sorted copy of the elements, not the actual elements themselves, I can't use XSL.

Here's some XML, a program out output

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 );
        }
    }

Here's the XML

<xml>
<ele value='3' test='Third'/>
<ele value='2' test='Second'/>
<ele value='1' test='First'/>
</xml>

Finally the output in document (descending) order. I'd like an XPath that returns the nodes in ascending order.

3
2
1

PS, I'm using System.Xml in Visual Studio 2008 .NET 3.5

like image 688
William Walseth Avatar asked Dec 09 '22 04:12

William Walseth


1 Answers

XPath doesn't supprort ordering, however you may look at AddSort method.

like image 160
Wojteq Avatar answered Dec 23 '22 13:12

Wojteq