XPath 查询以获取元素的第 n 个实例 [英] XPath query to get nth instance of an element

查看:53
本文介绍了XPath 查询以获取元素的第 n 个实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个 HTML 文件(我无法控制其内容),其中包含多个 input 元素,所有元素都具有相同的 "search_query"id 固定属性.文件的内容可以更改,但我知道我总是想获取第二个 input 元素,其 id 属性为 "search_query".

我需要一个 XPath 表达式来做到这一点.我试过 //input[@id="search_query"][2] 但这不起作用.这是此查询失败的示例 XML 字符串:

<表格><input id="search_query"/></表单>

<div><表格><input id="search_query"/></表单>

<div><表格><input id="search_query"/></表单>

请记住,以上只是一个例子,其他 HTML 代码可能完全不同,input 元素可以出现在没有一致文档结构的任何地方(除非我保证会有总是至少有两个 input 元素,其 id 属性为 "search_query").

正确的 XPath 表达式是什么?

解决方案

这是一个常见问题:

//somexpression[$N]

表示查找由 //somexpression 选择的每个节点,即其父节点的 $Nth 个子节点.

你想要的是:

(//input[@id="search_query"])[2]

记住:[] 运算符的优先级(优先级)高于 // 缩写.

There is an HTML file (whose contents I do not control) that has several input elements all with the same fixed id attribute of "search_query". The contents of the file can change, but I know that I always want to get the second input element with the id attribute "search_query".

I need an XPath expression to do this. I tried //input[@id="search_query"][2] but that does not work. Here is an example XML string where this query failed:

<div>
  <form>
    <input id="search_query" />
   </form>
</div>

<div>
  <form>
    <input id="search_query" />
  </form>
</div>

<div>
  <form>
    <input id="search_query" />
  </form>
</div>

Keep in mind that that the above is merely an example and the other HTML code can be quite different and the input elements can appear anywhere with no consistent document structure (except that I am guaranteed there will always be at least two input elements with an id attribute of "search_query").

What is the correct XPath expression?

解决方案

This is a FAQ:

//somexpression[$N]

means "Find every node selected by //somexpression that is the $Nth child of its parent".

What you want is:

(//input[@id="search_query"])[2]

Remember: The [] operator has higher precedence (priority) than the // abbreviation.

这篇关于XPath 查询以获取元素的第 n 个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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