Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find position of a node using XPath

Tags:

xpath

Anyone know how to get the position of a node using XPath?

Say I have the following xml:

<a>     <b>zyx</b>     <b>wvu</b>     <b>tsr</b>     <b>qpo</b> </a> 

I can use the following xpath query to select the third <b> node (<b>tsr</b>):

a/b[.='tsr'] 

Which is all well and good but I want to return the ordinal position of that node, something like:

a/b[.='tsr']/position() 

(but a bit more working!)

Is it even possible?

edit: Forgot to mention am using .net 2 so it's xpath 1.0!


Update: Ended up using James Sulak's excellent answer. For those that are interested here's my implementation in C#:

int position = doc.SelectNodes("a/b[.='tsr']/preceding-sibling::b").Count + 1;  // Check the node actually exists if (position > 1 || doc.SelectSingleNode("a/b[.='tsr']") != null) {     Console.WriteLine("Found at position = {0}", position); } 
like image 261
Wilfred Knievel Avatar asked Oct 22 '08 15:10

Wilfred Knievel


1 Answers

Try:

count(a/b[.='tsr']/preceding-sibling::*)+1. 
like image 153
James Sulak Avatar answered Oct 08 '22 18:10

James Sulak