你如何计算从包含另一个XQuery函数的xsl:for-each循环返回的结果数?

时间:2013-10-11 04:54:11

标签: xml xslt count xquery

我有以下XML:

<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="count-example.xsl"?>
<musiclist>
<mp3>
    <id>MP1003</id>
    <artist>Frank Sinatra</artist>
    <title>Fly Me To The Moon</title>
    <location path="home/music/sinatra/MP1008.mp3" />
</mp3>
<mp3>
    <id>MP1004</id>
    <artist>Frank Sinatra</artist>
    <title>New York, New York</title>
    <location path="home/music/sinatra/MP1004.mp3" />
</mp3>
<mp3>
    <id>MP1005</id>
    <artist>Frank Sinatra</artist>
    <title>Young At Heart</title>
    <location path="home/music/sinatra/MP1009.mp3" />
</mp3>
</musiclist>

以及以下XSL:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="musiclist">
    <xsl:for-each select="mp3">
        <xsl:variable name="idvar" select="id" />
        <xsl:if test="contains(location/@path, $idvar) = 0">
            false
        </xsl:if>
    </xsl:for-each>
</xsl:template>
</xsl:stylesheet>

XSL将输出False两次,因为我捕获的ID不在我想要的位置元素的path属性中。

如何计算此输出,即输出数字2作为此XSL的完整结果?

1 个答案:

答案 0 :(得分:0)

此处不需要 xsl:for-each ,您可以使用 count 函数来计算符合给定条件的节点数

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:template match="musiclist">
      <xsl:value-of select="count(mp3[contains(location/@path, id) = 0])" />
   </xsl:template>
</xsl:stylesheet>

表达式可能更好地重写为<xsl:value-of select="count(mp3[not(contains(location/@path, id))])" />,因为包含会返回true或false。

相关问题