Find position of a node using XPath


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

Say I have the following xml:


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


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


(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);

Best Solution


Related Question