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::
代替..
的请求的语法应该是什么?
我知道//attribute::vo/../text()
不是最佳的Xpath表达式。
//*[@vo]/text()
更好。
因此,无需用ancestor::
或parent::
代替..
。
如果您仍然想知道ancestor
的工作方式,则需要当前节点的父节点,当前节点的父节点等等,直到根为止。因此,您使用ancestor
的查询看起来像
//attribute::vo/ancestor::*[1]/title/text()
ancestor
表示您将要收集所有(祖父母)父母,*
表示您不在意那些(祖父母)父母将是什么节点,[1]
意味着您需要离当前节点“最近”。