INDIA +91 964 309 2571 | USA +1669 327 4700 info@navyuginfo.com

Preceding-sibling and following-sibling in xpath

navyugblog_1

Xpath: "//ul/li[contains(text(),'doprep')]/preceding-sibling::li"

This will give “Navyug”

How to get all the following siblings of doprep

Xpath:  "//ul/li[contains(text(),'doprep')]/following-sibling::li"

This will give all the preceding siblings ( soldier2ndlife, savior)

There is a trick to use preceding-sibling and following-sibling. the way you place them matters – So, when you use them at the beginning they would give you reverse result.

For Ex:

When you use preceding-sibling at the beginning then it will give you the result as ( soldier2ndlife, savior) instead of Navyug.

Xpath : "//li[preceding-sibling::li='doprep']"

This will give soldier2ndlife, savior.

when you use following-sibling at the beginning then it will give the reverse result. Instead of giving all below nodes of doprep, this will give Navyug.

Xpath:  "//li[following-sibling::li='doprep']"

Now the question is how to get all the nodes between doprep and Savior.

Xpath :  "//ul/li[preceding-sibling::li='doprep' and following-sibling::li='Savior']"

This will return soldier2ndlife

or

Xpath : "//ul/li[preceding-sibling::li[.='doprep'] and following-sibling::li[.='savior']]"

or

Xpath:  "//ul/li[preceding-sibling::li[contains(text(),'doprep')] and following-sibling::li[contains(text(),'Savior')]]"

Not every time, we can use absolute xpaths, there are cases where we need to use relative xpaths for dynamic elements. Such concepts may help an automation engineer to script quickly.

Although, chrome and firefox consoles provide you to extract the xpaths on a given page, if you want to practice more xpath expressions, you may use the below testbed:

http://www.whitebeam.org/library/guide/TechNotes/xpathtestbed.rhtm