raph.amiard
raph.amiard

Reputation: 2785

Combining the use of preceding and following sibling in the same xpath query

I have a quite simple problem but i can't seem to resolve it. Let's say i have the following code:

<a>
    <b property="p1">zyx</b>
    <b>wvu</b>
    <b>tsr</b>
    <b property="p2">qpo</b>
    <b>qcs</b>
</a>

I want to select the nodes between the b node who has a property="p1" and the b node who has property="p2". I can do either of those with the preceding-sibling and the following-sibling axis but I can't seem to find how to combine both.

Upvotes: 24

Views: 14880

Answers (3)

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243459

XPath 1.0:

/a/b[preceding-sibling::b/@property='p1' and following-sibling::b/@property='p2']

XPath 2.0:
The expression above has some quirks in XSLT 2.0, it is better to use the new and safer operators << (before) and >> (after).

/a/b[../b[@property='p2'] << . and . >> ../b[@property='p1']]

Upvotes: 21

user357812
user357812

Reputation:

Also, this XPath 1.0:

/a/b[preceding-sibling::b/@property='p1'][following-sibling::b/@property='p2']

Note: Don't use // as first step. Whenever you can replace and operator by predicates, do it.

In XPath 2.0:

/a/b[. >> ../b[@property='p1']][../b[@property='p2'] >> .]

Upvotes: 8

Paul Butcher
Paul Butcher

Reputation: 6956

You can combine the tests in the predicate using and.

Upvotes: -1

Related Questions