Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPATH -- Result order defined by query

Tags:

xpath

I have an xpath-expression like this:

element[@attr="a"] | element[@attr="b"] | element[@attr="c"] | … which is an »or« statement. So can I create an expression that guarantees the result to appear in the order as in the query, even if the elements appear in a different order in the document?

f.e. an document fragment in this order:

<doc>
    <element attr="c" />
    <element attr="b" />
    <element attr="a" />
    .
    .
    .
</doc>

and a result list ordered like this:

[0] <element attr="a" />
[1] <element attr="b" />
[2] <element attr="c" />
.
.
.
like image 595
philipp Avatar asked May 19 '26 04:05

philipp


1 Answers

The | operator computes the union of its operands and with XPath 1.0 you simply get a set of nodes, the order is undefined, though most XPath APIs then return the result in document order or allow you to say which order you want or whether order matters (see for instance http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult).

With XPath 2.0 you get a sequence of nodes ordered in document order, with XPath 2.0 if you want the order of your subexpressions you would need to use the comma operator, not the union operator i.e. element[@attr="a"] , element[@attr="b"] , element[@attr="c"].

So for e.g. /doc!(element[@attr="a"] , element[@attr="b"] , element[@attr="c"]) you get the element nodes in the wanted order.

XPath 3.1 online fiddle.

Of course you can also sort the elements in XPath 3.1 e.g.

sort(/doc/element, (), function($el) { $el/@attr })
like image 101
Martin Honnen Avatar answered May 20 '26 17:05

Martin Honnen