Вы находитесь на странице: 1из 3

By Bhanu Prakash (javagalbhanu@gmail.

com)

Siblings in Xpath
The nodes in the HTML tree have a hierarchical relationship to each other.The terms parent, child, and sibling are
used to describe the relationships. Parent nodes have children. Children on the same level are called siblings
(brothers or sisters).

 In a node tree, the top node is called the root


 Every node has exactly one parent, except the root (which has no parent)
 A node can have any number of children
 Siblings are nodes with the same parent

The following image illustrates a part of the node tree and the relationship between the nodes:

(For more details please visit: http://www.w3schools.com/htmldom/dom_nodes.asp)

Sample HTML code


<html>
<body>
<select id="city" multiple>
<option>Ahmadabad</option>
<option>Bangalore</option>
<option>Chennai</option>
</select>

</body>
</html>

Sample HTML Page


By Bhanu Prakash (javagalbhanu@gmail.com)

Xpath expression for Bangalore


Html Code:

<option>Bangalore</option>

Xpath expression:

//option[text()=’ Bangalore’]

Xpath expression for City which is after the Bangalore


Html Code:

<select id="city" multiple>


<option>Ahmadabad</option>
<option>Bangalore</option>
<option>Chennai</option>
</select>

Xpath expression:

//option[text()='Bangalore']/following-sibling::option

following-sibling is used to find the next element present under the same parent (in this example “Chennai”)

the syntax is:

following-sibling::htmlTag
By Bhanu Prakash (javagalbhanu@gmail.com)

Xpath expression for City which is before the Bangalore


Html Code:

<select id="city" multiple>


<option>Ahmadabad</option>
<option>Bangalore</option>
<option>Chennai</option>
</select>

Xpath expression:

//option[text()='Bangalore']/preceding-sibling::option

preceding-sibling is used to find previous element present under the same parent (in this example “Ahmadabad”)

the syntax is:

preceding -sibling::htmlTag

Please Note:
following-sibling will return all the element present next to the specified element under the same parent
preceding-sibling will return all the element present before the specified element under the same parent

Example:
//option[text()=’Ahmadabad’]/following-sibling ::option

The above xpath will identify both Bangalore and Chennai

We can use index to identify the individual elements

1st Next city of ’Ahmadabad’ ( Bangalore)

//option[text()=’Ahmadabad’]/following-sibling ::option[1]

2nd Next city of ’Ahmadabad’ (Chennai)


//option[text()=’Ahmadabad’]/following-sibling ::option[2]

Вам также может понравиться