How should i retrieve nodes where ALL children have gender = "male".
使用:
/*/parent[child
and
(not(child[not(@gender) or not(@gender='male')]))
]
这将选择所有parent
元素:
是 XML 文档顶部元素的子元素,并且
生个child
孩子,然后
其所有child
孩子都有一个gender
属性,并且
其所有child
子gender
属性的字符串值为“男”
在这里,我们使用了非常通用和有用的双重否定定律
你的第二个问题:
Q2 另外,我如何检索所有只有一个(男性)孩子的父母。
使用:
/*/parent[child[@gender='male']
and
not(child[2])
]
这选择:
作为 XML 文档顶部元素的子元素的任何parent
元素,以及
有一个child
孩子,其gender
属性的字符串值为“男性”,并且
那是没有第二个child
孩子。
基于 XSLT 的验证:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/">
<xsl:copy-of select=
"/*/parent[child
and
(not(child[not(@gender) or not(@gender='male')]))
]"/>
==========
<xsl:copy-of select=
"/*/parent[child[@gender='male']
and
not(child[2])
]"/>
</xsl:template>
</xsl:stylesheet>
当此转换应用于以下 XML 文档(提供的文档,已扩展以使其更具代表性)时:
<t>
<parent> a
<child gender="male">b</child>
<child gender="female">c</child>
<child gender="female">d</child>
</parent>
<parent> e
<child gender="male">f</child>
<child gender="male">g</child>
<child gender="female">h</child>
</parent>
<parent> z
<child gender="male">x</child>
<child gender="male">y</child>
</parent>
<parent> t
<child gender="male">u</child>
</parent>
</t>
计算两个 XPath 表达式,并将这些计算的结果(选定元素)复制到输出:
<parent> z
<child gender="male">x</child>
<child gender="male">y</child>
</parent>
<parent> t
<child gender="male">u</child>
</parent>
==========
<parent> t
<child gender="male">u</child>
</parent>