Wachburn
Wachburn

Reputation: 2939

reinitializing xslt variable

I have a variable:

<xsl:variable name="code" select="F2"/>

can I reinitializing it anywhere else in my code? is it possible?
I need save the current node in it and determine whether rejected it or pass in.

Upvotes: 1

Views: 224

Answers (3)

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243599

XSLT is a functional language. In functional languages variables, once given value, cannot be modified.

One can achieve the same effect as modifying a variable, by using xsl:param in a template and passing in a new invocation of the template a new value for this parameter.

Here is a short and complete example:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="nums">
  <xsl:call-template name="sum"/>
 </xsl:template>

 <xsl:template name="sum">
  <xsl:param name="pList" select="*"/>
  <xsl:param name="pAccum" select="0"/>

  <xsl:choose>
   <xsl:when test="not($pList)">
    <xsl:value-of select="$pAccum"/>
   </xsl:when>
   <xsl:otherwise>
     <xsl:call-template name="sum">
      <xsl:with-param name="pList"
           select="$pList[position() > 1]"/>
       <xsl:with-param name="pAccum" select="$pAccum+$pList[1]"/>
     </xsl:call-template>
   </xsl:otherwise>
  </xsl:choose>
 </xsl:template>
</xsl:stylesheet>

when this transformation is applied on this XML document:

<nums>
  <num>01</num>
  <num>02</num>
  <num>03</num>
  <num>04</num>
  <num>05</num>
  <num>06</num>
  <num>07</num>
  <num>08</num>
  <num>09</num>
  <num>10</num>
</nums>

the correct result is produced:

55

Do note how the parameters are "modified" :)

Upvotes: 2

StuartLC
StuartLC

Reputation: 107387

xsl:variables cannot be reassigned 'explicitly', although their scope is limited to the current construct (e.g. xsl:template or xsl:for-each), and so will be 're-initialized' as it traverses to the next 'each'.

xsl:variables can be pointed to a node, i.e.

<xsl:variable name="someNodeVar" select="xpathToElement"/>

and then used e.g.

<xsl:value-of select="$someNodeVar/relativeXpathGoesHere/text()"/>

Upvotes: 2

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56222

Once you have set a variable's value, you cannot change or modify that value!

Reference: http://www.w3schools.com/xsl/el_variable.asp

Upvotes: 3

Related Questions