In XSLT how do I increment a global variable from

2020-01-26 06:19发布

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?

8条回答
该账号已被封号
2楼-- · 2020-01-26 07:15

You can use the position() function to do what you want. It would look something like this.

<xsl:template match="/">
  <xsl:for-each select="section">
    <xsl:call-template name="section">
      <xsl:with-param name="counter" select="{position()}"/>
    </xsl:call-template>
  </xsl:for-each>
</xsl:template>

<xsl:template name="section">
  <xsl:param name="counter"/>
  <span class="title" id="title-{$counter}">
    <xsl:value-of select="title"/>
  </span>
</xsl:template>
查看更多
霸刀☆藐视天下
3楼-- · 2020-01-26 07:19

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:

<xsl:template match="a">
<xsl:param name="count" select="0">
  <xsl:apply-templates>
     <xsl:with-param select="$count+1"/>
  </xsl:apply-templates>
</xsl:template>

Also look at using generate-id() if you want to create ids.

查看更多
登录 后发表回答