Search code examples
xpath

How to locate sibling nodes with XPath


This is the experimental web page address
Please take a look at the image below; this is the node I really want to capture. Because it is very similar to the previous node:

 <div class="indent" id="dir_2567698_short" style="display: none;">, 

I used

 //*[contains(@class,'indent') and contains(@style,'display' )]/..

to find its parent node, and then used

/div[6]

to locate the actual target. However, the target node rankings may not always be in the 6th position; some may be in the 5th position. Therefore, I want to use

//*[contains(@class,'indent') and contains(@style,'display' )]/.

to first locate <div class="indent" id="dir_2567698_short" style="display: none;">. Then, I want to find its next sibling node at the same level, which will allow me to accurately find the target node. However, I have tried several methods without success. How can I find the 'next sibling node'?

Here are the methods I've tried but didn't work:

//*[contains(@class,'indent')and contains(@style,'display' )]/./div[1]
//*[contains(@class,'indent')and contains(@style,'display' )]/./div[0]

enter image description here


Solution

  • Ids in HTML are supposed to be unique so if you are looking for an element node with an id attribute like <div class="indent" id="dir_2567698_short" style="display: none;">, it seems //*[@id = 'dir_2567698_short'] or, if the XPath implementation supports the id function for HTML, even id('dir_2567698_short') should suffice.

    As for siblings, use preceding-sibling::*[1] or following-sibling::*[1], to find the first preceding or following sibling element.