renatoaraujoc
renatoaraujoc

Reputation: 357

XPath how to select an element where the following sibling has an specific child?

I'm trying hard to find an answer but I somehow can't figure out how to find an element who the next sibling has immediate child...

Example:

<p>text</p>
<p>
    <br/>
    <span>text2</span>
</p>

In this case how can I:

  1. Find all the <p> with text where it has an adjacent-sibling <p> with a first-child <br>, I guess this translates into p + p > br:first-child?
  2. Find all the <p> with text where it has an adjacent-sibling <p> with an any level child <br>, I guess this translates into p + p br?

What I have tried:

  1. //p[contains(., 'text') and following-sibling::p[br]]

1.1. //p[contains(., 'text') and following-sibling::p/*[br]]

1.2 //p[contains(., 'text')]/following-sibling::p[br]

Nothing works, any hope?

Thank you!

Upvotes: 0

Views: 784

Answers (1)

zx485
zx485

Reputation: 29022

Your first try was close, but it was checking if <p> has any following-siblings named <p> which have a child named <br>. But I guess that you really wanted to check if the first following-sibling named <p> has a child named <br> instead.

So use

//p[contains(., 'text') and following-sibling::p[1][br]]

To get the element only if <br> is the first child, you can use this extended expression

//p[contains(., 'text') and following-sibling::p[1][*[self::br and position()=1]]]

To satisfy your second requirement that <br> can be at any descendant level and not only a direct child, you can use

//p[contains(., 'text') and following-sibling::p[1][descendant-or-self::br]]

Upvotes: 3

Related Questions