有人知道如何使用 XPath 获取节点的位置吗?
假设我有以下 xml:
<a>
<b>zyx</b>
<b>wvu</b>
<b>tsr</b>
<b>qpo</b>
</a>
我可以使用以下 xpath 查询来选择第三个 <b> 节点 (<b>tsr</b>):
a/b[.='tsr']
这一切都很好,但我想返回该节点的序数位置,例如:
a/b[.='tsr']/position()
(但更多的工作!)
甚至可能吗?
编辑:忘了提到我正在使用.net 2,所以它是 xpath 1.0!
更新:最终使用了James Sulak的出色答案。对于那些感兴趣的人,这里是我在 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);
}