首页 > 解决方案 > 选择具有祖先条件的节点

问题描述

我的问题:我需要检查“testElement”的属性“attributeToBeTested”。“testElement”是“test”的唯一孩子。一个条件:这个“test”元素必须是“toto”的子元素,而不是“tata”或“titi”的子元素。

所以我把我的测试写成:

//toto/descendant::test/descendant::testElement[attribute::attributeToBeTested != "Z"] and //test[not(ancestor::tata)] and //test[not(ancestor::titi)]

我想我写的是:给我所有的“test”元素,“toto”的子元素,其中“testElement”元素的“attributeToBeTested”未设置为“Z”并且没有“tata”或“titi” “作为祖先。

但显然,这个测试是错误的,这让我发疯!

这是 XML 示例:

<tata>
  ....
  <test>
      <testElement attributeTobeTested="Z"/>
  </test>
</tata>
<toto>
  ....
  <test>
      <testElement attributeTobeTested="H"/>
  </test>
  ....
  <test>
      <testElement attributeTobeTested="Z"/>  <---- This one should pop up
  </test>
</toto>    
<toto>
  ....
  <titi>
      <test>
          <testElement attributeTobeTested="Z"/>
      </test>
  </titi>
</toto>    

只有一个应该弹出:“toto”内的那个不在“tata”中,也不在“titi”中,并且属性为“Z”

标签: xmlxpath

解决方案


试试下面的 XPath:

//toto//test[not(ancestor::*[name()=("titi", "tata")])]/testElement[@attributeTobeTested="Z"]

它应该返回您所需testElement的节点


推荐阅读