xml XPath 查询以获取元素的第 n 个实例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4007413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 13:22:06  来源:igfitidea点击:

XPath query to get nth instance of an element

xmlxpath

提问by rlandster

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

有一个 HTML 文件(我无法控制其内容),其中有几个input元素都具有相同的固定id属性"search_query". 文件的内容可以更改,但我知道我总是想获取input具有 id 属性的第二个元素"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:

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

<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 inputelements can appear anywhere with no consistent document structure (except that I am guaranteed there will always be at least two inputelements with an id attribute of "search_query").

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

What is the correct XPath expression?

什么是正确的 XPath 表达式?

回答by Dimitre Novatchev

This is a FAQ:

这是一个常见问题

//somexpression[$N]

//somexpression[$N]

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

意思是“找到它选择的每个节点//somexpression$N其父节点的第 th 个子节点”。

What you want is:

你想要的是

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

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

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

回答by rlandster

This seems to work:

这似乎有效:

/descendant::input[@id="search_query"][2]

I go this from "XSLT 2.0 and XPath 2.0 Programmer's Reference, 4th Edition" by Michael Kay.

我从 Michael Kay 的“XSLT 2.0 and XPath 2.0 Programmer's Reference, 4th Edition”中找到了这个。

There is also a note in the "Abbreviated Syntax" section of the XML Path Language specification http://www.w3.org/TR/xpath/#path-abbrevthat provided a clue.

XML 路径语言规范http://www.w3.org/TR/xpath/#path-abbrev的“缩写语法”部分中还有一条注释提供了线索。