XSLT Recursion Overview
XSLT depends on recursion as a looping mechanism. Recursion occurs when a section of code calls itself, either directly or indirectly. Both named and unnamed templates can use recursion, and different templates can use mutual recursion, one calling another that in turn calls the first.
To avoid infinite recursion and excessive consumption of system resources, the Junos OS management process (mgd) limits the maximum recursion to 5000 levels. If this limit is reached, the script fails.
In the following example, an unnamed template matches
on a <count>
element. It then calls
the <count-to-max>
template, passing
the value of the count
element as max
. The <count-to-max>
template starts by declaring both the max
and cur
parameters and setting the default
value of each to 1
(one). Although the
optional default value for max
is one,
the template will use the value passed in from the count
template. Then the current value of cur
is emitted in an <out>
element. Finally,
if cur
is less than max
, the <count-to-max>
template recursively
invokes itself, passing cur + 1
as cur
. This recursive pass then outputs the next number
and repeats the recursion until cur
equals max
.
<xsl:template match="count"> <xsl:call-template name="count-to-max"> <xsl:with-param name="max" select="."/> </xsl:call-template> </xsl:template> <xsl:template name="count-to-max"> <xsl:param name="cur" select="'1'"/> <xsl:param name="max" select="'1'"/> <out><xsl:value-of select="$cur"/></out> <xsl:if test="$cur < $max"> <xsl:call-template name="count-to-max"> <xsl:with-param name="cur" select="$cur + 1"/> <xsl:with-param name="max" select="$max"/> </xsl:call-template> </xsl:if> </xsl:template>
Given a max
value of 10
, the values contained in the <out>
tag are 1
, 2
, 3
, 4
, 5
, 6
, 7
, 8
, 9
, and 10
.