Reputation: 4323
Can someone tell me why the below xPath expression is resulting in the array being in the reverse order?
/ReaderDetails/Reader[Pin = "2325" or Pin = "2421" or Pin = "2424"]
When I then do a foreach
, the array that is returned pulls the element for 2424 first, then 2421 and last 2325.
These PINs are entered in a comma separated list, and need to be in this order.
Upvotes: 0
Views: 184
Reputation: 163352
If you're in XPath 1.0 (and I assume you are, because people using later versions generally mention the fact) then according to the XPath spec, the result is a node-set, and a node-set is literally a set of nodes with no defined order. However, all implementations I know of return the results of the node-set in document order, because that is how XSLT requires them, and most XPath implementations are designed with XSLT as an important use case. So the Reader
elements are likely to be returned in the order that they are encountered when scanning the document in a forwards direction.
In XPath 3.1 you could return a sequence of nodes in a chosen order by writing
/ReaderDetails ! (Reader[Pin = "2325"],
Reader[Pin = "2421"],
Reader[Pin = "2424"])
or perhaps (if the required order is always "sorted by Pin number"),
sort(/ReaderDetails/Reader[Pin = ('2325', '2421', '2424'), (),
function($r) {number($r!Pin})
but to do that you will need to install a different XPath engine, such as Saxon/C.
It's not possible to return a sequence of nodes in non-document-order in XPath 1.0 because there is no such data type. The only collection data type in XPath 1.0 is the node-set, which as I mentioned has no prescribed order. Therefore your only option with XPath 1.0 is to retrieve the nodes one at a time using separate XPath expressions, or perhaps to sort the nodes within the calling application.
Upvotes: 1