xml 仅查找第一次出现的 XPath 表达式是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14294997/
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
What is the XPath expression to find only the first occurrence?
提问by Narin
I used this Xpath expression "//span[@class='Big']"and got all elements in that page that are under <span>tag and class='Big'.
我使用了这个 Xpath 表达式"//span[@class='Big']"并获取了该页面中<span>标记和class='Big'.
My question is what if I want just the first occurrence on the page, not all occurrences, what would be the correct Xpathexpression?
我的问题是,如果我只想要页面上的第一次出现,而不是所有出现,那么正确的Xpath表达是什么?
Thanks, Narin
谢谢,纳林
回答by Dimitre Novatchev
The correct answer (note the brackets):
正确答案(注意括号):
(//span[@class='Big'])[1]
The following expression is wrong in the general case:
以下表达式在一般情况下是错误的:
//span[@class='Big'][1]
because it selects every spanelement in the document, that satisfies the condition in the first predicate, and that is the first such child of its parent-- there can be many such elements in an XML document and all of them will be selected.
因为它选择span文档中的每个元素,满足第一个谓词中的条件,并且是其父元素的第一个这样的子元素——在一个 XML 文档中可以有很多这样的元素,它们都将被选中。
For more detailed explanation see: https://stackoverflow.com/a/5818966/36305
更详细的解释见:https: //stackoverflow.com/a/5818966/36305
回答by Grant Miller
Dimitre Novatchev's answer is correct if you are expecting the classattribute to be equal toBig(without any other classes attached to the element):
如果您希望class属性等于Big(没有附加到元素的任何其他类),Dimitre Novatchev 的回答是正确的:
(//span[@class="Big"])[1]
... which is similar to the following JavaScript expression:
...类似于以下 JavaScript 表达式:
document.querySelectorAll('span[class="Big"]')[0]
On the other hand, if you are expecting Bigto be one of any numberof classes in the classattribute (rather than the only class), you can use the following expression:
另一方面,如果您希望Big成为属性中任意数量的类之一class(而不是唯一的类),则可以使用以下表达式:
(//span[contains(concat(" ", normalize-space(@class), " "), " Big ")])[1]
... which is similar to the following JavaScript expression:
...类似于以下 JavaScript 表达式:
document.querySelectorAll('span.Big')[0]

