descendant-or-self轴选取当前节点及其所有后代节点,如下使用descendant-or-self::*可选中自身及、、,而descendant轴不包含自身,self轴仅选自身,结合谓语可实现精准查询。

XPath的
descendant-or-self
轴,顾名思义,包含当前节点自身,以及该节点的所有后代节点。可以理解为“我以及我的所有子孙”。
解决方案:
descendant-or-self
轴在XPath表达式中非常实用,它允许你从一个节点开始,选取该节点及其所有后代节点。这在处理层级结构的XML或HTML文档时尤其有用。
如何更准确理解descendant-or-self轴?
简单来说,
descendant-or-self::node()
会选取当前节点以及当前节点下的所有节点,无论这些节点嵌套多少层。 想象一棵树,
descendant-or-self
会选取树根(当前节点)以及树上的所有枝干和叶子(所有后代节点)。
举个例子,假设我们有以下XML片段:
<bookstore><book category="cooking"><title lang="en">Everyday Italian</title> <author>Giada De Laurentiis</author></book></bookstore>
如果当前节点是
<bookstore></bookstore>
,那么
descendant-or-self::*
将会选取
<bookstore></bookstore>
,
<book></book>
,
<title></title>
,
<author></author>
这四个节点。
*
是通配符,表示选取所有类型的节点。 如果我们使用
descendant-or-self::title
, 那么只会选取
<title></title>
节点。
descendant-or-self轴与其他轴的区别是什么?
descendant-or-self
轴经常与
descendant
轴混淆。
descendant
轴只选取当前节点的所有后代节点,不包括当前节点自身。 还是用上面的例子,如果当前节点是
<bookstore></bookstore>
,那么
descendant::*
将会选取
<book></book>
,
<title></title>
,
<author></author>
这三个节点,而不会选取
<bookstore></bookstore>
自身。
另外,
self
轴只选取当前节点自身。 如果当前节点是
<bookstore></bookstore>
,那么
self::*
只会选取
<bookstore></bookstore>
。
理解这些轴之间的区别,对于编写精确的XPath表达式至关重要。
在实际应用中,如何高效使用descendant-or-self轴?
在实际应用中,
descendant-or-self
轴可以用来搜索特定类型的节点,或者查找具有特定属性的节点。 例如,假设我们想要选取所有包含
title
标签的节点(包括作为顶层节点和后代节点),可以使用以下XPath表达式:
//descendant-or-self::title
这个表达式会选取文档中所有名为
title
的节点。
另一个例子,假设我们想选取所有具有
lang
属性的节点,可以使用以下XPath表达式:
//descendant-or-self::*[@lang]
这个表达式会选取文档中所有具有
lang
属性的节点,无论它们是什么类型。
[@lang]
是一个属性选择器,表示选取具有
lang
属性的节点。
此外, 结合
descendant-or-self
和谓语(predicate)可以实现更复杂的查询。 谓语是放在方括号
[]
中的条件表达式,用于过滤节点。 例如, 选取所有
bookstore
及其后代中
author
节点文本内容为 "Giada De Laurentiis" 的节点:
//bookstore/descendant-or-self::author[text()='Giada De Laurentiis']
总而言之, 掌握
descendant-or-self
轴及其与其他轴的区别, 能够帮助你更有效地使用 XPath 查询 XML 或 HTML 文档中的数据。











