Reputation: 105
I have the following xml :
<pax>
<age>5</age>
</pax>
<pax>
<age>5</age>
</pax>
<pax>
<age>12</age>
</pax>
And the follwoing xslt:
<xsl:for-each select="paxes/pax">
<xsl:variable name="PaxAge" select="age"/>
<COUNT>
<xsl:value-of select='count(paxes/pax/age[text()=$PaxAge])'/>
</COUNT>
</xsl:for-each>
However the result I get in count is always
<COUNT>0</COUNT>
<COUNT>0</COUNT>
<COUNT>0</COUNT>
If I change it to
<xsl:value-of select='count(paxes/pax/age[text()="5"])'/>
I will receive
<COUNT>2</COUNT>
<COUNT>2</COUNT>
<COUNT>2</COUNT>
The output should be:
<COUNT>2</COUNT>
<COUNT>1</COUNT>
How can I get the write count for each iterate?
Upvotes: 2
Views: 800
Reputation: 163595
You say you want one COUNT element in the output for each distinct value of age. That makes it a grouping query. In XSLT 2.0, you can therefore use the grouping query:
<xsl:for-each-group select="paxes/pax/age" group-by=".">
<COUNT><xsl:value-of select="count(current-group())"/></COUNT>
</xsl:for-each-group>
If you're stuck with XSLT 1.0, grouping queries are much tricker, but you can use the technnique of Muenchian grouping with keys, as illustrated in the answer from @Rnet.
Upvotes: 2
Reputation: 5040
Assuming you're trying to count the occurrences this should work,
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:key name="age" match="/paxes/pax/age" use="." />
<xsl:template match="/">
<xsl:for-each select="paxes/pax/age[generate-id(.) = generate-id(key('age', .)[1])]">
<COUNT>
<!-- optional -->
<xsl:attribute name="age">
<xsl:value-of select="."/>
</xsl:attribute>
<xsl:value-of select="count(key('age',.))"/>
</COUNT>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
should give an xml like:
<COUNT age="5">2</COUNT>
<COUNT age="12">1</COUNT>
Upvotes: 2