我无法清楚地理解使用//element
和/descendant::element
在XPath中选择基本元素的多个子元素时的区别.
给出这个HTML片段
<html>
<body>
<div class="popupContent">
<table>
<tr class="aclass"><td> Hello </td> <td> <input type="text" value="FIRST" /> </td></tr>
<tr class="aclass"><td> Goodbye </td> <td> <input type="text" value="SECOND" /> </td></tr>
</table>
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
我需要input
根据它在表格中的位置来选择每个.
//div[@class='popupContent']//input[1]
这选择第一个输入,
//div[@class='popupContent']//input[2]
这给出错误,
//div[@class='popupContent']/descendant::input[1]
这再次选择第一个输入,
//div[@class='popupContent']/descendant::input[2]
这选择第二个输入
使用/descendant::input
我需要的东西:抓住所有输入,让我按位置选择.
怎么不一样//
?为什么它只返回第一个元素而不是之后的元素?
我知道这个问题,但答案基本上说它们是别名并指向文档,我无法理解,缺乏一个具体的例子.
最近我需要在HTML文档的节点上评估一个XQuery.基本上,我需要从body元素的第一个子元素中选择具有href属性的所有元素.我添加了一个小例子来解释:
<html>
<body>
<a href="http://www.google.be"/>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
在这种情况下,所需的提取结果显然是:
<a href="http://www.google.be"/>
Run Code Online (Sandbox Code Playgroud)
我的第一个想法是使用//body/*[1]//*[@href]
因为:
//body
匹配body元素,无论它在哪里/*[1]
匹配body元素的第一个子元素//*[@href]
匹配当前元素的所有后代或self我认为这可行,但在提供的示例中,XQuery没有给出任何结果.
但是,我读了一下,发现了以下内容(来源:http://www.keller.com/xslt/8/):
Alternate notation for "//": descendant-or-self::node()
Run Code Online (Sandbox Code Playgroud)
所以我改变了我的XQuery //body/*[1]/descendant-or-self::node()[@href]
,这次,结果是正确的.
我的问题://和descendant-or-self :: node()之间有什么区别?我在这里找到的(在xpath中//节点和/ descendant :: node之间有什么区别?)和这里(http://www.w3.org/TR/xpath/#axes)说:
//
是的缩写/descendant-or-self::node()/
.例如,//para
简称/descendant-or-self::node()/child::para
.
这导致我得出结论//
并且/descendant-or-self::node()
不可互换(可能是因为最后终止/
?),但是有人可以告诉我是否有速记/descendant-or-self::node()
?