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="/">
      <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 name="COUNTER">
     <xsl:value-of select="count(../ns5:Custom/ns6:ShipmentStop)"/>
  <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 name="SEQ_COUNTER">
   <xsl:when test="$LOOP1_COUNTER='0'">
     <xsl:value-of select="$LOOP2_COUNTER"/>
     <xsl:value-of select="($LOOP1_COUNTER*$COUNTER)+$LOOP2_COUNTER"/>
     <xsl:value-of select="number($NN) +number($SEQ_COUNTER)"/>

No comments: