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);
}
Unlike stated previously 'preceding-sibling' is really the axis to use, not 'preceding' which does something completely different, it selects everything in the document that is before the start tag of the current node. (see http://www.w3schools.com/xpath/xpath_axes.asp)
Try:
If you ever upgrade to XPath 2.0, note that it provides function index-of, it solves problem this way:
Where:
You can do this with XSLT but I'm not sure about straight XPath.
I do a lot of Novell Identity Manager stuff, and XPATH in that context looks a little different.
Assume the value you are looking for is in a string variable, called TARGET, then the XPATH would be:
Additionally it was pointed out that to save a few characters of space, the following would work as well:
I also posted a prettier version of this at Novell's Cool Solutions: Using XPATH to get the position node
I realize that the post is ancient.. but..
replace'ing the asterisk with the nodename would give you better results
instead of