A node -set has no order (the set is in order unordered). Most XPath APIs present the result of a node-set from evaluating an XPath expression in document order, which you observe and report in your question.
XPath is a read-only query language, and therefore it never changes the structure of the source XML document β the nodes in the node node of the selected nodes coincide with their structure in the original XML document. The structure, among other things, includes order.
If you need nodes returned in a different order than their original order in the XML document, this cannot be done only with XPath .
For this purpose, you can use XSLT:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:strip-space elements="*"/> <xsl:template match="node()|@*"> <xsl:copy> <xsl:apply-templates select="node()|@*"/> </xsl:copy> </xsl:template> <xsl:template match="library"> <xsl:apply-templates select="*[not(position() >2)]"> <xsl:sort select="position()" data-type="number" order="descending"/> </xsl:apply-templates> </xsl:template> </xsl:stylesheet>
when this conversion is applied to the provided XML document:
<library> <book name="book1"> hello </book> <book name="book2"> world </book> <book name="book3"> !!! </book> </library>
the desired, correct result is output:
<book name="book2"> world </book> <book name="book1"> hello </book>
source share