Tuesday, December 4, 2012

Incrementing Logic in XSL for SEQUENCE in multiple for-loops



I had a requirement where there was multiple for-loops and they wanted to increment the sequence value in loop under the inner loop but counter should be unique irrespective of the loop.
I will take the example of ShipmentItem &ShipmentStop. So if there are 2 ShipmentItems and 3 ShipmentStops then it should be incremented from 1 to 6. Since XSL
Doesn’t support out-of-the box increment as it is not a programming logic,I had to look for a work-around.
ShipmentItem records will form the outer loop and ShipmentStop records the inner loop.
So for using the increment logic I used count(preceding-sibling:: NODE) function .

I am attaching the XSL code snippet for easier implementation and understanding.

$SEQ_COUNTER variable will have the unique sequence ID.

  
  <xsl:template match="/">
    <top:testCollection>
      <xsl:for-each select="/eboebo:UpdateShipmentEBM/eboebo:DataArea/eboebo:UpdateShipment/ns5:ShipmentItem">
  <xsl:variable name="LOOP1_COUNTER">
     <xsl:value-of select="count(preceding-sibling::ns5:ShipmentItem)"/>
   </xsl:variable>
  <xsl:variable name="COUNTER">
     <xsl:value-of select="count(../ns5:Custom/ns6:ShipmentStop)"/>
  </xsl:variable>     
     
  <xsl:for-each select="../ns5:Custom/ns6:ShipmentStop">
    
   <!--looping logic for sequence ids  -->
  <xsl:variable name="LOOP2_COUNTER">
    <xsl:value-of select="count(preceding-sibling::ns6:ShipmentStop)+1"/>
  </xsl:variable>
  <xsl:variable name="SEQ_COUNTER">
   <xsl:choose>
   <xsl:when test="$LOOP1_COUNTER='0'">
     <xsl:value-of select="$LOOP2_COUNTER"/>
   </xsl:when>
   <xsl:otherwise>
     <xsl:value-of select="($LOOP1_COUNTER*$COUNTER)+$LOOP2_COUNTER"/>
   </xsl:otherwise>
   </xsl:choose>
    </xsl:variable>
    <top:test1>
    
   <top:ID_counter>
    
     <xsl:value-of select="number($NN) +number($SEQ_COUNTER)"/>
   </top:ID_counter>
     
     ................
     .............
     
   <top:test1>   
   
     </xsl:for-each>
          
        </xsl:for-each>