tags:

views:

37

answers:

3

Hi

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.

A: 

You can combine the tests in the predicate using and.

Paul Butcher
Indeed, spelled out it would read something like: `//b[preceding-sibling::b/@property='p1' and following-sibling::b/@property='p2']`
Wrikken
Wrikken : ok thank you. I didn't know i could use preceding and following sibling like that, i only ever saw it used like "b[@property="p1"]/following-sibling::*"Paul Butcher : i knew that, but thank you for taking the time to answer
raph.amiard
+1  A: 

Also, this XPath 1.0:

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

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

In XPath 2.0:

/a/b[. >> ../b[@property='p1']][../b[@property='p2'] >> .]
Alejandro
Thank you for your answer, exactly what i need. But i'm curious as to why would you replace and by another predicate ?
raph.amiard
@raph.amiard: From http://www.w3.org/TR/xpath/#booleans: "An and expression is evaluated by evaluating each operand". So, if left operand is false, right operand will be evaluate any way. With predicates, only for those nodes that pass first filter, the second predicate will be apply on them. For XPath 2.0, this MAY be not the case.
Alejandro
+1  A: 

XPath 1.0:

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

XPath 2.0:

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

Dimitre Novatchev
@Dimitre: It's looks like we were thinking in this at the same time. Ja!
Alejandro
@Alejandro: Yes, but I think using "and" is safer than using a sequence of two predicates.
Dimitre Novatchev