问题描述
XPath -(//first//*)[1]
和 //first//*[1]
有什么区别?它是如何工作的?
XPath -What is the difference between (//first//*)[1]
and //first//*[1]
?How it works?
示例 XML 文件是:
A sample XML file is:
<root>
<first>
<second>
Test
</second>
<second>
<third>Test2</third>
</second>
</first>
</root>
(//first///*)[1] 给出:
<second>
Test
</second>
但是//first///*[1] 给出:
<second>
Test
</second>
<third>Test2</third>
推荐答案
两种情况下,//first
选择所有first
元素,//first//*
选择 first
的所有元素后代.那么,区别在于:
In both cases, //first
select all first
elements, and //first//*
selects all elements descendents of first
. Then, the difference is:
(//first//*)[1]
从所有这些元素中选择,只有 first.//first///*[1]
从所有这些元素中选择每个第一个子元素.
(//first//*)[1]
selects from all of those elements, only the first.//first//*[1]
selects from all of those elements, every first child.
正如您在 XML 中看到的那样,second
被 XPath #1 选中,因为它是第一个第一
.(您的元素名称选择有点不理想.)second
和 third
都被 XPath #2 选中,因为它们都是 在他们各自的兄弟姐妹中排名第一.
As you've seen for your XML, second
is selected by XPath #1 because it is the first of all the descendents of first
. (Your element name choices are a bit non-ideal.) Both second
and third
are selected by XPath #2 because they're both first among their respective siblings.
这篇关于XPath - (//first///*)[1] vs//first////[1]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!