Search code examples
xmlxsltforeachjdeveloper

XSLT: Get sum of count from for-each loop


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 Partial XSLT

<xsl:for-each select = "/PURCHASE_ORDER_DISPATCH/MsgData/Transaction/PO_POD_HDR_EVW1/PO_ID">
    <xsl:variable name = "N1Count" select = "count(..)"/>
    <xsl:variable name = "PO1Count" select = "count(../PO_POD_LN_EVW1)"/>

    <xsl:variable name = "TotalSeg">
        <xsl:value-of select = "normalize-space((2 * $N1Count) + $PO1Count)" 
                                xmlns:xsl = "http://www.w3.org/1999/XSL/Transform"/>
    </xsl:variable>

    <EDI_TXN_850P.VERSION_1:EDI_FLD_96>
        <xsl:value-of select="normalize-space($TotalSeg + 5.0)"/>
    </EDI_TXN_850P.VERSION_1:EDI_FLD_96>
</xsl:for-each>

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.

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).

How do i make this happen using XSLT.

Thanks


Solution

  • You don't want to use count() inside a loop. It will already count all of the instances in a tree fragment, so you can do it without a loop:

    <xsl:variable name = "TotalSeg">
        <xsl:value-of select = 
           "normalize-space((2 * 
            count(/PURCHASE_ORDER_DISPATCH/MsgData/Transaction/PO_POD_HDR_EVW1)) + 
            count(/PURCHASE_ORDER_DISPATCH/MsgData/Transaction/PO_POD_HDR_EVW1/PO_POD_LN_EVW1))
           "
        />
    </xsl:variable>
    
    <EDI_TXN_850P.VERSION_1:EDI_FLD_96>
        <xsl:value-of select="normalize-space($TotalSeg + 5.0)"/>
    </EDI_TXN_850P.VERSION_1:EDI_FLD_96>