XPath:如何通过索引选择具有某些属性的节点? [英] XPath: How to select node with some attribute by index?

查看:21
本文介绍了XPath:如何通过索引选择具有某些属性的节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个具有特定属性的节点,我需要通过索引选择其中之一.例如,我需要选择带有 'test' 类的第二个

- //div[@class='test'][2] 不起作用.

有没有办法通过索引选择具有某些属性的节点?怎么做?

解决方案

这是一个常见问题.

在 XPath 中,[] 运算符比 // 伪运算符具有更高的优先级(绑定更强).

因此,表达式:

//div[@class='test'][2]

选择所有 class 属性为test"并且谁(div 元素)是第二个这样的 div 的 div 元素 父母的孩子.这不是你想要的.

使用:

(//div[@class='test'])[2]

I have several nodes with some particular attribute and I need to select one of them by index. For example I need to select second <div> with 'test' class - //div[@class='test'][2] doesn't work.

Is there a way to select node with some attribute by index ? How to do it?

解决方案

This is a FAQ.

In XPath the [] operator has a higher precedence (binds stronger) than the // pseudo-operator.

Because of this, the expression:

//div[@class='test'][2]

selects all div elements whose class attribute is "test" and who (the div elements) are the second such div child of their parent. This is not what you want.

Use:

(//div[@class='test'])[2]

这篇关于XPath:如何通过索引选择具有某些属性的节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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