I am processing an XML file where I want to keep count of the number of nodes, so that I can use it as an ID as I write new nodes.
At the moment I have a global variable called 'counter'. I am able to access it within a template, but I haven't found a way of manipulating it within a template.
Here is a condensed version of my XSLT file:
<xsl:variable name="counter" select="1" as="xs:integer"/>
<xsl:template match="/">
<xsl:for-each select="section">
<xsl:call-template name="section"></xsl:call-template>
</xsl:for-each>
</xsl:template>
<xsl:template name="section">
<!-- Increment 'counter' here -->
<span class="title" id="title-{$counter}"><xsl:value-of select="title"/></span>
</xsl:template>
Any suggestions how to go from here?
You can use the position() function to do what you want. It would look something like this.
XSLT variables cannot be changed. You'll have pass the value along from template to template.
If you are using XSLT 2.0, you can have parameters and use tunneling to propagate the variable to the right templates.
Your template will look something like this:
Also look at using generate-id() if you want to create ids.