title: XSLT: Get sum of count from for-each loop
body: <p>I have an XSLT program, where I'm trying to get the sum of the count from a for-each loop. But it's returning only the last loops sum. Please find the below <strong>Partial XSLT</strong> </p>
  
  <pre><code>&lt;xsl:for-each select = "/PURCHASE_ORDER_DISPATCH/MsgData/Transaction/PO_POD_HDR_EVW1/PO_ID"&gt;
      &lt;xsl:variable name = "N1Count" select = "count(..)"/&gt;
      &lt;xsl:variable name = "PO1Count" select = "count(../PO_POD_LN_EVW1)"/&gt;
  
      &lt;xsl:variable name = "TotalSeg"&gt;
          &lt;xsl:value-of select = "normalize-space((2 * $N1Count) + $PO1Count)" 
                                  xmlns:xsl = "http://www.w3.org/1999/XSL/Transform"/&gt;
      &lt;/xsl:variable&gt;
  
      &lt;EDI_TXN_850P.VERSION_1:EDI_FLD_96&gt;
          &lt;xsl:value-of select="normalize-space($TotalSeg + 5.0)"/&gt;
      &lt;/EDI_TXN_850P.VERSION_1:EDI_FLD_96&gt;
  &lt;/xsl:for-each&gt;
  </code></pre>
  
  <p>In the above for-each loop basically, i'm getting count for N1 and PO1 and then after some calculations, trying to assign the ((2* $N1Count) + $PO1Count) to $TotalSeg variable. The problem is it is getting only the latest/recent most loop.</p>
  
  <p>For example, if i have two loops to go through, let's say $N1Count = 2, $PO1Count = 3 in first loop and $N1Count = 2, $PO1Count = 5 in second, the $TotalSeg is getting assigned only ((2 * 2) + 5) = 9 (second loops values) instead of ((2 * 4) + 8 ) = 16 (sum of all values). </p>
  
  <p>How do i make this happen using XSLT.</p>
  
  <p>Thanks</p>