Malik Abdullah
Malik Abdullah

Reputation: 1

XSLT - add value to global variable in loop

I have following XSLT. I want to add the values of specific covers in sumcontents variable, but it is not summing up. It is always showing up 0 value. Can someone please guide, how can I achieve this.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">

        <xsl:param name="sumContents">0.00</xsl:param>

        <MSMTransformer>
            <Recordtype>
                <xsl:value-of select="MSMARKETPOLICY/RECORDTYPE"></xsl:value-of>
            </Recordtype>


            <xsl:for-each select="MSMARKETPOLICY/POLICY/ITEMS/ITEM">
                <xsl:for-each select="RISKS/RISK">
                    <xsl:choose>
                        <xsl:when
                            test="(COVERS/COVER[COVERAGE='BLDG']) and (COVERS/COVER[COVERAGE='CNTS'])">
                            <TypeOfCover>Buildings and Contents</TypeOfCover>
                            <xsl:value-of select="$sumContents + COVER/TBASICPRM" />
                        </xsl:when>

                        <xsl:when test="COVERS/COVER[COVERAGE='BLDG']">
                            <TypeOfCover>Buildings</TypeOfCover>
                        </xsl:when>
                        <xsl:when test="COVERS/COVER[COVERAGE='CNTS']">
                            <TypeOfCover>Contents</TypeOfCover>
                            <xsl:value-of select="$sumContents + COVER/TBASICPRM" />
                        </xsl:when>
                    </xsl:choose>
                </xsl:for-each>
            </xsl:for-each>

            <ValueOfContentsInsured>
                <xsl:value-of select="$sumContents"></xsl:value-of>
            </ValueOfContentsInsured>

        </MSMTransformer>
    </xsl:template>
</xsl:stylesheet>

Upvotes: 0

Views: 1049

Answers (1)

Michael Kay
Michael Kay

Reputation: 163458

XSLT is a functional programming language. Among other things this means that variables in XSLT are immutable, and that the for-each instruction is not a loop, it is a mapping expression (that is, it conceptually processes all the items in the input sequence simultaneously, not one after the other).

To sum the value of elements with a specific condition, you don't want xsl:for-each, you want something like sum(RISKS/RISK/COVERS/COVER[COVERAGE='CNTS' or COVERAGE='BLDG']/TBASICPRM)

Upvotes: 1

Related Questions