Monday, October 19, 2015

Using preceding-sibling and following-sibling in xpath

In this article I will show few examples about how to use following-sibling and preceding-sibling

Our XML example we are going to use.
 <div id="cities">  
 <country>France</country>  
   <city>Paris</city>  
   <country>UK</country>  
   <city>London</city>  
   <city>Manchester</city>  
   <city>Liverpool</city>  
   <country>Denmark</country>  
   <city>Copenhagen</city>  
   <country>Ukraine</country>  
   <city>Kiev</city>  
   <city>Odessa</city>  
 </div>  

Taking all city elements after element UK

 /div/country[.='UK']/following-sibling::city  
 <city>London</city>  
 <city>Manchester</city>  
 <city>Liverpool</city>  
 <city>Copenhagen</city>  
 <city>Kiev</city>  
 <city>Odessa</city>  

Taking all city elements before element Denmark

 /div/country[.='Denmark']/preceding-sibling::city  
 <city>Paris</city>  
 <city>London</city>  
 <city>Manchester</city>  
 <city>Liverpool</city>  

Let's increase difficulty little bit and try to use preceding-sibling and following-sibling in the brackets []

Taking all city elements following till first country is UK

 /div/city[following-sibling::country='Denmark']  
 <city>Paris</city>  
 <city>London</city>  
 <city>Manchester</city>  
 <city>Liverpool</city>  

Taking all city elements from bottom till first country is Denmark

 /div/city[preceding-sibling::country='Denmark']  
 <city>Copenhagen</city>  
 <city>Kiev</city>  
 <city>Odessa</city>  

Let's increase difficulty even more and start using both preceding-sibling and following-sibling in one xpath.

Taking all city elements between two elements

In this example I'm going to get cities after UK and before Ukraine.
 /div/city[preceding-sibling::country='UK' and following-sibling::country='Ukraine']  
 <city>London</city>  
 <city>Manchester</city>  
 <city>Liverpool</city>  
 <city>Copenhagen</city>  

6 comments :

Anonymous said...

thanks for putting this together! this helped me in ways a lot of the one off StackOverflow threads weren't able to.

Anonymous said...

Thanks a lot, it really help me to understabd

Anonymous said...

Just a minor correction:
Your heading for the 3rd example should read "Taking all city elements till next country is Denmark" rather than "Taking all city elements following till first country is UK"

Unknown said...
This comment has been removed by the author.
Unknown said...
This comment has been removed by the author.
Unknown said...

this is a very good explanation on preceding and following sibling's

I had a question like this:

- In the same example what if I need to get the city's between two country's while iterating over countries.



abstract code
for /div/country
cities = XPath for the cities b/w current iterating country and the next country