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);
}
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…