Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

combining XPATH axes (preceding-sibling & following-sibling)

Tags:

axes

xpath

Say I have the following UL:

<ul>
  <li>barry</li>
  <li>bob</li>
  <li>carl</li>
  <li>dave</li>
  <li>roger</li>
  <li>steve</li>
</ul>

I need to grab all the LIs between bob & roger. I can grab everything after bob with //ul/li[contains(.,"bob")]/following-sibling::li, and I can grab everything before roger with //ul/li[contains(.,"roger")]/preceding-sibling::li. The problem is when I try to combine the two, I end up getting extra results.

For example, //ul/li[contains(.,"bob")]/following-sibling::li[contains(.,"roger")]/preceding-sibling::li will of course get everything before roger, instead of ignoring the items before bob.

Is there a way to chain these two xpaths together?

like image 880
MrGlass Avatar asked Mar 26 '12 20:03

MrGlass


People also ask

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.

How can I get next sibling in XPath?

To traverse to the next sibling, we have to use the following-sibling concept in xpath. This will allow us to traverse to the next sibling from the present sibling of the same parent. Let us try to move from the first child<h1> of parent <div> to the second <h2> as in the above image.

How do you find the XPath of an element by its previous element?

We can find an element using the xpath locator with Selenium webdriver. To identify the element with xpath, the expression should be //tagname[@attribute='value']. To identify the element with xpath, the expression should be //tagname[@class='value']. There can be two types of xpath – relative and absolute.

How do you write parent and child in XPath?

So, we will first find the XPath of the current node. XPath(Current node): //input[@id = 'text']. We will then find the XPath of the parent element node of the current node using parent syntax, as shown below screenshot. XPath of the Parent node: //input[@id = 'text']//parent::span.


1 Answers

Try:

/ul/li[preceding-sibling::li='bob' and following-sibling::li='roger']
like image 157
Daniel Haley Avatar answered Sep 21 '22 07:09

Daniel Haley