使用 XPath 查找节点的位置 [英] Find position of a node using XPath

查看:24
本文介绍了使用 XPath 查找节点的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道如何使用 XPath 获取节点的位置吗?

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

假设我有以下 xml:

Say I have the following xml:

<a>
    <b>zyx</b>
    <b>wvu</b>
    <b>tsr</b>
    <b>qpo</b>
</a>

我可以使用以下 xpath 查询来选择第三个 <b>节点 (<b>tsr</b>):

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

(但需要更多工作!)

有可能吗?

编辑:忘记提及我使用的是 .net 2 所以它是 xpath 1.0!

edit: Forgot to mention am using .net 2 so it's xpath 1.0!

更新:最终使用了 James Sulak很好的答案.对于那些感兴趣的人,这里是我在 C# 中的实现:

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

推荐答案

尝试:

count(a/b[.='tsr']/preceding-sibling::*)+1.

这篇关于使用 XPath 查找节点的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆