xml 如何在 XPath 中识别多个具有相同名称的元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/321805/
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 12:13:18  来源:igfitidea点击:

How can you identify multiple elements with the same name in XPath?

xmlxpath

提问by user41129

What if I had a document that had multiple elements with the same name -- how would I retrieve, for instance, the second element?

如果我有一个包含多个同名元素的文档怎么办——例如,我将如何检索第二个元素?

<doc>
...
 <element name="same">foo</element>
...
 <element name="same">bar</element>
...
 <element name="same">baz</element>
...
</doc>

I'd expect something like //elem[@name='same'][2] to work.

我希望像 //elem[@name='same'][2] 这样的东西能够工作。

Additionally, how would I find the second from last element in xpath with a variable number of elements with the same name

此外,我如何在 xpath 中找到具有可变数量的同名元素的倒数第二个元素

回答by Dimitre Novatchev

[ ]has higher priority than // (and "//" is actually only an abbreviation, not an operator). This is so, because according to the XPath 1.0 Spec,

[ ]具有比 // 更高的优先级(并且“//”实际上只是一个缩写,而不是运算符)。之所以如此,是因为根据XPath 1.0 Spec

"// is short for /descendant-or-self::node()/"

“// 是 /descendant-or-self::node()/ 的缩写”

and later:

然后:

"NOTE: The location path //para[1]does not mean the same as the location path /descendant::para[1]. The latter selects the first descendant para element; the former selects all descendant para elements that are the first para children of their parents."

注意:位置路径//para[1]与位置路径的含义不同/descendant::para[1]。后者选择第一个后代 para 元素;前者选择所有后代 para 元素,它们是其父元素的第一个 para 子元素。”

Therefore, the XPath expression:

因此,XPath 表达式:

     //element[@name='same'][2]

     //element[@name='same'][2]

means:

方法:

Select any element in the document, that is named "element", has an attribute "name" with value "same", and this element is the second such child of its parent.

选择文档中名为“element”的任何元素,具有值为“same”的属性“name”,并且该元素是其父元素的第二个这样的子元素。

What you want is:

你想要的是

     (//element[@name='same'])[2]

     (//element[@name='same'])[2]

Note the brackets, which override the higher precedence of [].

注意括号,它覆盖了 [] 的更高优先级。

Similarly, the last but one such nodeis selected by the following XPath expression:

类似地,最后一个这样的节点由以下 XPath 表达式选择:

     (//element[@name='same'])[last()-1]

     (//element[@name='same'])[last()-1]

Finally, a necessary warning: The use of the "//" abbreviation is very expensive as it causes the whole (sub)tree to be traversed. Whenever the structure of the document is known, it is recommended to use more specific constructs (location paths).

最后,一个必要的警告:“//”缩写的使用非常昂贵,因为它会导致遍历整个(子)树。每当知道文档的结构时,建议使用更具体的结构(位置路径)。