获取XPath中可选属性的父属性

时间:2015-01-03 12:45:29

标签: xml xpath

<?xml version="1.0" encoding="utf-8"?>
<client name="test">
  <projects active="true">
   <project id="pr1" active="false" />
   <project id="pr2" active="true" />
   <project id="pr3" />
 </projects>
</client>

对于上述情况,我需要获取具有active =&#34; true&#34;的项目。如果它已在元素级别设置。如果不是那么我需要转到父元素并对活动元素进行细化并检查它。

我们需要获取所有项目元素,因此应返回

<project id="pr2" />
<project id="pr3" />

我使用了以下但不起作用:

//project/ancestor-or-self::node()/@active[position()=1]

请帮忙。

2 个答案:

答案 0 :(得分:4)

以下XPath表达式产生正确的结果:

/client/projects/project[@active = 'true' or (../@active = 'true' and not(@active = 'false'))]

转换为

/client/projects/project         Find an outermost element node "client", all its child
                                 elements "projects" and all child elements "project"
                                 of "projects".
[@active = 'true'                But only return them if there is an attribute "active"
                                 with a value "true"
or (../@active = 'true'          or if its parent has an attribute "active" with its
                                 value set to "true" 
and not(@active = 'false'))]     and at the same time there's no attribute "active" on
                                 the "project" element set to "false".

并返回

<project id="pr2" active="true"/>
-----------------------
<project id="pr3"/>

或许稍微不同的变体更有意义:

/client/projects/project[@active = 'true' or (not(@active) and ../@active = 'true')]

结果是一样的。

答案 1 :(得分:1)

尝试

//project[(ancestor-or-self::*/@active)[last()] = 'true']