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

问题描述 投票:0回答:2

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::代替..的请求的语法应该是什么?

xml xpath
2个回答
0
投票

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

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

因此,无需用ancestor::parent::代替..


0
投票

如果您仍然想知道ancestor的工作方式,则需要当前节点的父节点,当前节点的父节点等等,直到根为止。因此,您使用ancestor的查询看起来像

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

ancestor表示您将要收集所有(祖父母)父母,*表示您不在意那些(祖父母)父母将是什么节点,[1]意味着您需要离当前节点“最近”。

© www.soinside.com 2019 - 2024. All rights reserved.