XSLT计算具有特定文本节点的元素

时间:2018-04-13 09:35:22

标签: xslt

XML:

<?xml version="1.0" encoding="UTF-8"?>
<PetShop>
    <Cage>
        <Occupant1>Parrot</Occupant1>
        <Occupant2>Parrot</Occupant2>
    </Cage>
    <Cage>
        <Occupant1>Monkey</Occupant1>
        <Occupant2>Parrot</Occupant2>
    </Cage>
    <Cage>
        <Occupant1>Parrot</Occupant1>
        <Occupant2>Parrot</Occupant2>
    </Cage>
    <Cage>
        <Occupant1>Parrot</Occupant1>
        <Occupant2>Monkey</Occupant2>
    </Cage>
</PetShop>

XSLT:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
    <html>
        <body>
            <xsl:apply-templates />
        </body>
    </html>
</xsl:template>

<xsl:template match="PetShop">
    <ul>
        <li>Occupant 1 Parrots: <xsl:value-of select="count(//Cage/Occupant1[text() = 'Parrot'])"/></li>
        <li>Occupant 2 Monkeys: <xsl:value-of select="count(//Cage/Occupant2[text() = 'Monkey'])"/></li>
        <li>Occupant 1 Parrots with Occupant 2 Monkeys: <xsl:value-of select="count(//Cage/Occupant1[text() = 'Parrot'] and /Occupant2[text()='Monkey'])" /></li>
    </ul>
</xsl:template>

我的问题是这样的:我想得到那些占用者1是“鹦鹉”的笼子数量。而且乘员2是“猴子”。使用上面的样式表。这是另一篇文章(Count xml elements with multiple conditions and precise properties)的类似问题,其中Lingamurthy CS的解决方案是:

count(home/place[property[@Name='Type' and @Value='house'] and property[@Name='Context' and @Value='kitchen']])

但是,我不能让它对我的文本节点起作用。非常感谢任何帮助!提前谢谢。

1 个答案:

答案 0 :(得分:1)

这将为您提供其中Occupant1为Parrot且Occupant2为Monkey的笼子数。

count(/PetShop/Cage[Occupant1 = 'Parrot' and Occupant2 = 'Monkey'])

在PetShop的上下文中,只需:

count(Cage[Occupant1 = 'Parrot' and Occupant2 = 'Monkey'])