Blog

Preceding-sibling and following-sibling in xpath

How to use preceding-sibling and following-sibling in xpath to find sibling nodes:

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 trick to use preceding-sibling and following-sibling. the way you place them matters – So, when you use them at beginning they would give you reverse result.

For Ex:

When you use preceding-sibling at 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 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, but if you want to practice more xpath expressions, you may use the below test bed:

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

By – Vishal Singh, Software QA Lead

adminPreceding-sibling and following-sibling in xpath
Share this post

Join the conversation