Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select the first preceding-sibling which has a particular node as child?

I have been trying to write a XPath statement which will select the first preceding-sibling of a node. That sibling should have a particular node as its child.

For example:

<a>
    <c></c>
    ....
    <b></b>
</a>

<a></a>
....
....
<a></a>

<a>
   <b> start </b>
</a>

In the above XML, if my context is at the node a which has start text inside its child b. How can I select the preceding node a whose child is b?

I tried preceding-sibling::*[b][1] but it only selects the node a if b is its first child. I also tried preceding-sibling::*[1][b] but it only checks the first preceding a node and if it doesn't contains b, the test fails.

Note: I am using XSLT 1.0

Can anyone suggest me a solution?

Thnx in advance!!

like image 252
Surender Thakran Avatar asked Feb 11 '14 07:02

Surender Thakran


2 Answers

I believe that:

preceding-sibling::*[b][1]

or preferably:

preceding-sibling::a[b][1]

should work just fine.

I tried preceding-sibling::*[b][1] but it only selects the node a if b is its first child.

I don't think that is so.

like image 77
michael.hor257k Avatar answered Sep 16 '22 17:09

michael.hor257k


Like this. ("The first preceding sibling who has a <b> child"):

preceding-sibling::a[b][1]

or this ("The first preceding sibling but only if it has a <b> child"):

preceding-sibling::a[1][b]

Multiple predicates must be true one after another. Therefore, this:

preceding-sibling::a[b and position() = 1]

is equivalent to the second expression, but not to the first.

like image 36
Tomalak Avatar answered Sep 19 '22 17:09

Tomalak