祖先的语法::在 Xpath 表达式中



xpath -e '//attribute::vo/../text()' books.xml

返回具有名为vo的属性的每个元素的内容。

例如,使用此book.xml

<bookstore>
<book category="cooking">
<title lang="en" vo="it">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title lang="en" vo="fr">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="web">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>

然后请求:

xpath -e '//attribute::vo/../text()' books.xml

给:

Found 2 nodes in /tmp/books.xml:
-- NODE --
Everyday Italian
-- NODE --
XQuery Kick Start

具有相同结果但用ancestor::代替..的请求的语法应该是什么?

如果你仍然想知道ancestor是如何工作的,它会把当前节点的父节点、当前节点的祖父级等带到根。因此,您使用ancestor的查询看起来像

//attribute::vo/ancestor::*[1]/title/text()

其中ancestor意味着你要收集所有的(祖(父节点,*意味着你不关心这些(祖(父节点是什么,[1]意味着你需要"最接近"当前节点的节点。

以下查询将生成相同的结果:

//attribute::vo/ancestor::book/title/text()

因为它不需要根元素,因为它不是book节点。所以我们在这里有"扁平"层次结构。

以下查询将仅采用具有"Web"类别的书籍(这不是您实际询问的内容,但可能会更清楚地了解如何使用轴(:

//attribute::vo/ancestor::book[@category='web']/title/text()

我知道//attribute::vo/../text()不是自然的Xpath表达式。

//*[@vo]/text()更好。

因此,无需引入ancestor::parent::来代替..

最新更新