简体   繁体   中英

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

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>

Firstly, count(..) is always going to return 1, because your selected node always has one parent.

Secondly, this is a functional language so you can't increment a value as you go round a loop. If you don't understand that, then do some reading.

You want an expression outside the for-each loop something like

select="2*count(XXXX) + count(/PURCHASE_ORDER_DISPATCH/MsgData/Transaction/PO_POD_HDR_EVW1/PO_POD_LN_EVW1)"

but I don't know what you intended to count with XXXX.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM