Search code examples
xsltxslt-1.0xslt-2.0

Is there a way to count the elements generated by an XSL within the same XSL?


If I have an XSL that creates output like this simple/rough example:

<Parent1>
  <ABC><xsl:value-of select="SomeValue1"/></ABC>
  <DEF><xsl:value-of select="SomeValue2"/></DEF>
  <GHI><xsl:value-of select="SomeValue3"/></GHI>
  ... 
  <YZ><xsl:value-of select="SomeValue9"/></YZ>
</Parent1>

... within this same XSL, how can I count how many children the XSL will produce?


Solution

  • You can generate your content into a variable, count the children in the variable, and then emit the content of the variable:

    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
        
        <xsl:template match="/">
            <xsl:variable name="temp-results">
                <Parent1>
                    <ABC><xsl:value-of select="SomeValue1"/></ABC>
                    <DEF><xsl:value-of select="SomeValue2"/></DEF>
                    <GHI><xsl:value-of select="SomeValue3"/></GHI>
                    ... 
                    <YZ><xsl:value-of select="SomeValue9"/></YZ>
                </Parent1>
            </xsl:variable>
            
            <xsl:text>Number of children:</xsl:text>
            <xsl:value-of select="count($temp-results/Parent1/*)"/>
            <xsl:sequence select="$temp-results"/>
        </xsl:template>
    </xsl:stylesheet>