首页 > 解决方案 > XPath:选择特定父节点的子节点

问题描述

有几种情况

案例一:

<Root>
  <Defaults Id="a"></Defaults>
</Root>

案例B:

<Root>
  <Repeat>
    <Defaults Id="b"></Defaults>
  </Repeat>
</Root>

案例 C(嵌套“重复”的数量可能是无限的):

<Root>
  <Repeat>
    <Repeat>
      <Repeat>
        <Defaults Id="c"></Defaults>
      </Repeat>
    </Repeat>
  </Repeat>
</Root>

案例 D:

<Root>
  <Repeat>
    <Page Id="p1">
      <Defaults Id="d"></Defaults>
    </Page>
  </Repeat>
</Root>

我需要返回属于根元素或仅位于重复节点内部的默认节点的 XPath 查询。如果至少一个父节点不是重复节点或根节点,则不应将它们包含在结果中。因此查询结果应该返回测试用例 A、B、C 的节点。

谢谢!

标签: xmlxpath

解决方案


这个 XPath,

//Defaults[parent::Root or parent::Repeat]

将选择Default父级为Rootor的所有元素Repeat

<Defaults Id="a"></Defaults>
<Defaults Id="b"></Defaults>
<Defaults Id="c"></Defaults>

按照要求。


推荐阅读