Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath sibling extraction

Tags:

xml

xslt

xpath

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
like image 742
user1522091 Avatar asked Jul 12 '12 22:07

user1522091


People also ask

How can I reach sibling in XPath?

We can use the XPath following sibling axis to find this. So, for this scenario, the XPath expression will be. And we need to identify its sibling “div ” element, as shown below. However, if numerous siblings have the same node, XPath will recognise all of the different elements.

What is sibling XPath in Selenium?

We can use the concept of following-sibling in xpath for identifying elements in Selenium. It identifies the siblings of the context node. The siblings should be located at the equal level of the existing node and should have the same parent.

What is preceding sibling in XPath?

The preceding-sibling axis indicates all the nodes that have the same parent as the context node and appear before the context node in the source document.


1 Answers

Use this XPath:

//p[preceding-sibling::h4[1][. = 'July 13']]
like image 155
Kirill Polishchuk Avatar answered Sep 23 '22 18:09

Kirill Polishchuk