newday
newday

Reputation: 3878

Understaning recursion in xslt

I am trying to understand recorsion in xslt. Can anybody explain what's happening in this code.

<xsl:template name="factorial">
  <xsl:param name="number" select="1"/>
  <xsl:choose>
    <xsl:when test="$number <= 1">
      <xsl:value-of select="1"/>
    </xsl:when>
    <xsl:otherwise>
      <xsl:variable name="recursive_result">
        <xsl:call-template name="factorial">
          <xsl:with-param name="number" select="$number - 1"/>
        </xsl:call-template>
      </xsl:variable>
      <xsl:value-of select="$number * $recursive_result"/>
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>

I can't understand why we wrap factorial template with <xsl:variable name="recursive_result">.

If there is more clear example is available, please guide me to that. I am lack of knowledge in recursion.

Upvotes: 0

Views: 1656

Answers (3)

Sakthivel
Sakthivel

Reputation: 666

In XSLT, we are using recursion instead of Looping. Recursion is nothing but a particular type of function that calls itself as many times when required to find the final solution. So,

  1. input the number variable as '1'
  2. The given value if it is less than 1 then it simply print the value of $number
  3. otherwise, it is move to call-template as input for the variable number with help of with-param
  4. here, it is calling the same templates again and pass value to same variable named as number
  5. Then the result value will be assigned to the variable recursive_result

Hope would be understand.

Upvotes: 0

OkieOth
OkieOth

Reputation: 3714

You can't declare global variables in XSLT that are changeable from other parts of the script. If you need a result from a template call or a recursion is the only way to "print out" the generated result in a variable.

The "print out" is done with the <xsl:value-of ... statement.

Upvotes: 1

Paul Butcher
Paul Butcher

Reputation: 6956

The call-template element is wrapped with the variable element in order to assign the result of calling it to the variable recursive_result.

This is done so that it can then be multiplied by number on the following line, to produce the final result.

Upvotes: 1

Related Questions