Tuesday, November 6, 2012

Looping In XSL

XSL is a functional language and not a programming language !! XSL variables are not actually variables, once set you cannot change their value !! Why is a for loop not working inside XSL !!

I hope many of us have encountered these questions while using XSL. I have come across many scenarios where I had to create a XSL to iterate through a XML and generate some output but looping is tricky inside XSL. Sure you can run a while loop inside BPEL and get your values assigned but that's clumsy.

Below is some sample code snippet which can be extended based on your requirements and should come handy when trying to loop inside XSL.

  <xsl:template match="/">
  <root>
     <xsl:call-template name="loop">
         <xsl:with-param name="i" select="1" /> 
         <xsl:with-param name="count" select="//code to find the counter for loop" /> 
     </xsl:call-template>
  </root>
  </xsl:template>

  <xsl:template name="loop">
     <xsl:param name="i" /> 
     <xsl:param name="count" /> 
     <xsl:if test="$i <= $count">
        //your code here.You can use the predicate [position() = $i] for correct assignments.
           <xsl:call-template name="loop">
           <xsl:with-param name="i" select="$i + 1" /> 
           <xsl:with-param name="count" select="$count" /> 
           </xsl:call-template>
     </xsl:if>
  </xsl:template>
Hope this helps..