Monday, 30 March 2015

Using for loop in XSL

By default xsl supports the for-each functionality which will iterate over the number of elements in source xml.
But what if we need something like for loop in normal programming language??
like for (int i=0;i<10 ;i++)

Solution:
We can achieve the above requirement with the help of callable template as described below,


 <xsl:template name="party">
    <xsl:param name="count"/>
    <xsl:param name="xml"/>

    <xsl:if test=" $count > 0">
            <name>
                  <xsl:value-of select="$xml/name"/>
          </name>
     </xsl:if>     
      <xsl:call-template name="party">
            <xsl:with-param name="count" select="$count - 1"/>
            <xsl:with-param name="xml" select="/"/>
        </xsl:call-template>  
  </xsl:template>          
       
   
Call the above template like this,

        <xsl:call-template name="party">
            <xsl:with-param name="count" select="6"/>
            <xsl:with-param name="xml" select="/"/>
        </xsl:call-template>           
                   
 
Above code creates the tag six times.

In this you can see how to access the source xml in the templates.
As you will not have direct access to the source xml in the callable template we need to pass it as parameter and use in the template.

No comments:

Post a Comment