有人知道如何使用 XPath 获取节点的位置吗?
假设我有以下 xml:
<a>
<b>zyx</b>
<b>wvu</b>
<b>tsr</b>
<b>qpo</b>
</a>
我可以使用以下 xpath 查询来选择第三个 节点 (tsr):
a/b[.='tsr']
这一切都很好,但我想返回该节点的序数位置,例如:
a/b[.='tsr']/position()
(但还需要更多工作!)
这可能吗?
编辑:忘记提及我使用的是 .net 2,所以它是 xpath 1.0!
<小时/>更新:最终使用 James Sulak的excellent answer 。对于那些感兴趣的人,这是我在 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);
}
最佳答案
尝试:
count(a/b[.='tsr']/preceding-sibling::*)+1.
关于xpath - 使用 XPath 查找节点的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/226405/