user1522091
user1522091

Reputation: 187

XPath sibling extraction

Example document:

<h4 class="bla">July 12</h4>
<p>Tim</p>
<p>Jon</p>
<h4 class="bla">July 13</h4>
<p>James</p>
<p>Eric</p>
<p>Jerry</p>
<p>Susie</p>
<h4 class="date">July 14</h4>
<p>Kami</p>
<p>Darryl</p>

What I want to do is grab all p nodes that were posted on July 13. Note that they are siblings of h4 and not children. So in this example, I'd like to get the p nodes that hold the following names: James, Eric, Jerry, and Susie.

I got close with the following, but it chose all p nodes that came after the July 13th h4 node, since they're all siblings. In other words, it didn't have a stop condition.

//h4[string() = 'July 13']/following-sibling::p

Upvotes: 9

Views: 3833

Answers (2)

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56162

Use this XPath:

//p[preceding-sibling::h4[1][. = 'July 13']]

Upvotes: 8

dan radu
dan radu

Reputation: 2782

Try this:

//p[preceding-sibling::h4/text() = 'July 13' and following-sibling::h4/text() = 'July 14']

Upvotes: 0

Related Questions