使用XPath 2.0/3.0选择路径不含B节点的A的后代C节点
选取符合条件的C节点的XPath表达式
XPath 2.0 优先方案
//C[ancestor::A[1] and not(ancestor::B[. >> ancestor::A[1]])]
表达式解释
//C:匹配文档中所有C节点ancestor::A[1]:筛选出存在最近A祖先的C节点(确保C是A的后代)not(ancestor::B[. >> ancestor::A[1]]):排除那些在「最近A祖先到C的路径区间内」包含B节点的C。其中>>是XPath 2.0的节点顺序比较运算符,用来判断B节点是否位于A到C的路径中。
示例验证
针对你提供的XML结构:
<Root> <Other> <A> <Other> <C/> <!-- 会被选中:最近A到该C的路径无B节点 --> </Other> <Other> <B> <Other> <C/> <!-- 不会被选中:路径中存在B节点 --> </Other> </B> </Other> </A> </Other> </Root>
第一个C满足所有条件会被选中,第二个C因路径包含B被排除。
XPath 3.0 可选方案
如果使用XPath 3.0,可采用逻辑更直观的遍历写法:
for $a in //A, $c in $a//C where every $node in $a/ancestor-or-self::* intersect $c/ancestor::* satisfies not($node[self::B]) return $c
该写法遍历每个A节点及其后代C,逐一验证A到C的路径节点中是否不存在B,可读性更强。
内容的提问来源于stack exchange,提问作者fractor
相关产品推荐
相关产品推荐

