使用XPath选择没有指定中间节点的后代节点

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

使用 XPath 2.0(理想情况下)或 3.0(可选),我想选择一个节点

C
,它是
A
的后代,只要从
A
C
的路径不包含任何
B
节点。

<Root>
  <Other>
    <A>
      <Other>
        <C/> <!--selected-->
      </Other>
      <Other>
        <B>
          <Other>
            <C/> <!--not selected-->
          </Other>
        </B>
      </Other>
    </A>
  </Other>
</Root>

Other
表示0个或多个嵌套的非
B
节点。

A
可能有
B
祖先。

xpath xpath-2.0
2个回答
2
投票

使用 XPath 2.0,我认为

//A//C[not(ancestor::B intersect ancestor::A[1]//B)]
就足够了。但请注意,Microsoft 的 XPath 实现是 XPath 1.0。


0
投票

我会写

//A/(.//C except .//B//C)

除非它是一个非常大的文档并且性能是一个问题,在这种情况下我可能会实现我自己的传递闭包

(child::* except child::B)

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