如何用带嵌套条件(引用外部元素值)的XPath查询符合条件的书籍
需求与问题描述
需要查询XML中作者获奖的书籍,同时输出书籍名称和对应作者的宠物名。XML结构中仅含一个城市,但包含大量书籍与作者,尝试的XPath语句无法正确关联当前书籍对应的作者。
XML示例
<?xml version="1.0" encoding="UTF-8"?> <root> <books> <book> <name>Fantastic World of Peggy</name> <category>fiction</category> <author-ref>/SanDiego/Peter</author-ref> </book> </books> <cities> <name>SanDiego</name> <authors> <author> <name>Peter</name> <awards-won>true</awards-won> <pet>pike</pet> </author> </authors> </cities> </root>
尝试的无效XPath语句
//books[category = 'fiction' and //author[name = string-after(<the-current-book>/author-ref, '/SanDiego/') and awards-won = 'true']]
//books[category = 'fiction']/concat(name, concat(' - ', //author[name = string-after(<the-current-book>/author-ref, '/SanDiego/') and awards-won = 'true']/pet))
可行的XPath写法
1. XPath 1.0 版本
XPath 1.0不支持string-after,需用substring-after处理作者引用,核心是用**当前上下文节点.**指代当前book,避免全局查询的匹配错误:
筛选符合条件的书籍节点
//book[category='fiction' and /root/cities/authors/author[name=substring-after(./author-ref, '/SanDiego/') and awards-won='true']]
直接输出书籍名称与作者宠物名的组合
//book[category='fiction' and /root/cities/authors/author[name=substring-after(./author-ref, '/SanDiego/') and awards-won='true']]/concat(name, ' - ', /root/cities/authors/author[name=substring-after(current()/author-ref, '/SanDiego/') and awards-won='true']/pet)
2. XPath 2.0+ 版本
支持string-after,写法更简洁,可用current()明确指代当前上下文的book节点:
筛选书籍节点
//book[category='fiction' and /root/cities/authors/author[name=string-after(author-ref, '/SanDiego/') and awards-won='true']]
输出组合内容
//book[category='fiction' and /root/cities/authors/author[name=string-after(author-ref, '/SanDiego/') and awards-won='true']]/concat(name, ' - ', /root/cities/authors/author[name=string-after(current()/author-ref, '/SanDiego/') and awards-won='true']/pet)
关键说明
- 用
.或current()替代你之前的<the-current-book>占位符,精准指代当前遍历的book节点; - 限定作者查询路径为
/root/cities/authors/author,避免全局//author带来的无关匹配; - XPath 1.0需用
substring-after替代string-after,后者是2.0及以上版本的专属函数。
内容的提问来源于stack exchange,提问作者RedX
相关产品推荐
相关产品推荐

