Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the total number of elements (iterations) in an XSLT for-each loop

Tags:

xml

xslt

I normally use jquery templates for this sort of thing but I inherited an XSLT file I need to update but I can't find a way to get the total number of elements (iterations) for a specific template call.

With jquery templates I'd do something like this and it would give me total number of assets that I'm looping through.

<span id="${spnID}">
    ${GroupName} (${Assets.length})
</span>

This would return me "Product x (5)" if there were five elements in the loop.

It seems simple but I can't seem to find a way to do the same thing with XSLT. Something like this, I think:

<span id="{$SpnId}">
    <xsl:value-of select="$GroupName"/> (<xsl:value-of select="$total-number-of-elements"/>)
</span>
like image 507
Aaron Avatar asked Dec 12 '22 06:12

Aaron


1 Answers

If you're looping over some $set then output count($set) to get the total number of items to be iterated. For example, try this stylesheet:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text" />
    <xsl:template match="/">
        <xsl:variable name="set" select="/table/row" />
        <xsl:variable name="count" select="count($set)" />
        <xsl:for-each select="$set">
            <xsl:value-of select="concat(position(), ' of ', $count, '&#xa;')" />
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

Against this input:

<table>
    <row id="1" />
    <row id="2" />
    <row id="3" />
    <row id="4" />
    <row id="5" />
    <row id="6" />
</table>

Output:

1 of 6
2 of 6
3 of 6
4 of 6
5 of 6
6 of 6

Note that we're looping over the nodes selected by /table/row and outputting count(/table/row) to get the number of iterations.

like image 134
Wayne Avatar answered May 16 '23 03:05

Wayne