在 XPath 中获取可选属性的父属性
Fetching parent attribute for optional attributes in 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="true" 的项目,以防它被设置在元素级别。如果不是,那么我需要转到父元素并调整活动元素并检查它。
我们需要获取所有项目元素,因此这应该 return
<project id="pr2" />
<project id="pr3" />
我使用了以下但它不起作用:
//project/ancestor-or-self::node()/@active[position()=1]
请帮忙。
以下 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".
和returns
<project id="pr2" active="true"/>
-----------------------
<project id="pr3"/>
或者稍微不同的变体可能更有意义:
/client/projects/project[@active = 'true' or (not(@active) and ../@active = 'true')]
结果是一样的
尝试
//project[(ancestor-or-self::*/@active)[last()] = 'true']
<?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="true" 的项目,以防它被设置在元素级别。如果不是,那么我需要转到父元素并调整活动元素并检查它。
我们需要获取所有项目元素,因此这应该 return
<project id="pr2" />
<project id="pr3" />
我使用了以下但它不起作用:
//project/ancestor-or-self::node()/@active[position()=1]
请帮忙。
以下 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".
和returns
<project id="pr2" active="true"/>
-----------------------
<project id="pr3"/>
或者稍微不同的变体可能更有意义:
/client/projects/project[@active = 'true' or (not(@active) and ../@active = 'true')]
结果是一样的
尝试
//project[(ancestor-or-self::*/@active)[last()] = 'true']