2

XPATH 1.0 相当于在 SQL 中使用嵌套查询和“ALL”关键字。例如,考虑以下代码段。

<parent> a <child gender = "male">b</child>
<child gender = "female>c</child></parent>
<parent> z <child gender = "male"> y </child></parent>

我应该如何检索所有孩子都具有性别 =“男性”的节点。这可以在 SQL 中通过编写一个子查询来返回孩子的性别,然后用 ALL 关键字嵌套它以检查所有孩子是否都是男性来完成。

Q2 另外,我如何检索所有只有一个(男性)孩子的父母。还要考虑父节点可能有其他节点。计算父母有名字“孩子”的孩子的数量,并检查孩子是否是我正在考虑解决问题的方式。这是最好的方法还是有更好的方法?

注意:在我的作业中,我面临一个需要类似查询的问题。我试图自己找到答案,但找不到。请帮忙

4

3 回答 3

1

ALL:选择有孩子但没有非男性孩子的父母:

//parent[child and not child[@gender!="male"]]

选择只有一个男孩的父母 - 选择只有一个孩子且有男孩的父母:

//parent[count(child)=1 and child[@gender="male"]]
于 2012-10-14T22:09:09.053 回答
1
How should i retrieve nodes where ALL children have gender = "male". 

使用

/*/parent[child
        and
          (not(child[not(@gender) or not(@gender='male')]))
         ]

这将选择所有parent元素

  1. 是 XML 文档顶部元素的子元素,并且

  2. 生个child孩子,然后

  3. 其所有child孩子都有一个gender属性,并且

  4. 其所有childgender属性的字符串值为“男”

在这里,我们使用了非常通用和有用的双重否定定律

你的第二个问题

Q2 另外,我如何检索所有只有一个(男性)孩子的父母。

使用

/*/parent[child[@gender='male']
        and
          not(child[2])
         ]

这选择

  1. 作为 XML 文档顶部元素的子元素的任何parent元素,以及

  2. 有一个child孩子,其gender属性的字符串值为“男性”,并且

  3. 那是没有第二个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>
于 2012-10-14T23:05:19.577 回答
1

我应该如何检索所有孩子都具有性别 =“男性”的节点。

一些受访者将此解释为意味着必须至少有一个孩子。但是您要求等效于 SQL 的 ALL 运算符,我相信在 SQL 中(如在数学逻辑中),如果应用于空集,则 ALL 返回 true。(所有的独角兽都有两个角——给我看一个没有的。)

因此,我认为对您的问题的严格回答将删除 Dimitre 在他的回答中包含的“孩子和”。但 Dimitre 可能猜对了,你所要求的并不是你真正想要的。

于 2012-10-15T07:37:15.230 回答