xml 仅使用 XPath 选择第一个实例?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/453191/
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
Select first instance only with XPath?
提问by Mat
I am parsing some XML something like this:
我正在解析一些像这样的 XML:
<root>
<some_gunk/>
<dupe_node>
...
stuff I want
...
</dupe_node>
<bits_and_pieces/>
<other_gunk/>
<dupe_node>
...
stuff I don't want
...
</dupe_node>
<more_gunk/>
</root>
An XPath of '//dupe_node'will give me two instances of dupe_nodeto play with. I only want to traverse the first. Can I do this with XPath?
一个 XPath'//dupe_node'会给我两个dupe_node可以玩的实例。我只想遍历第一个。我可以用 XPath 做到这一点吗?
回答by Azat Razetdinov
/descendant::dupe_node[1]
//dupe_node[1]is generally wrong, although it produces an identical result in this particular case. See docs:
//dupe_node[1]通常是错误的,尽管在这种特殊情况下它会产生相同的结果。请参阅文档:
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 元素。
Given the following XML:
给定以下 XML:
<foo>
<bar/>
<foo>
<bar/>
</foo>
</foo>
//bar[1]will produce two nodes, because both bars are first children of their respective parents.
//bar[1]将产生两个节点,因为两个条形都是它们各自父节点的第一个子节点。
/descendant::bar[1]will give only one node, which is the first of all the bars in the document.
/descendant::bar[1]将只给出一个节点,它是文档中所有条形中的第一个。
回答by Simon Willison
//dupe_node[1]
XPath counts from 1, not 0 in this case. You can use this tool to try things out in your browser:
XPath 从 1 开始计数,在这种情况下不是 0。您可以使用此工具在浏览器中进行尝试:
回答by Jonas Elfstr?m
//dupe_node[1]
//dupe_node[1]

