Dana Williams
Dana Williams

Reputation: 13

XSLT 2.0 - Sum Element Names that Increment

I'm working on generating a sum of element names that when they exist increment up.

XML Example:

<Distributions>
<DIST_DISTRIBUTIONMETHOD_1>Check to Other</DIST_DISTRIBUTIONMETHOD_1>
<DIST_CREDITOR_1>MOTORS FINANCE</DIST_CREDITOR_1>
<DIST_AMOUNT_1>16710.04</DIST_AMOUNT_1>
<DIST_NET_1>No</DIST_NET_1>
<DIST_DISTRIBUTIONMETHOD_2>Check to Other</DIST_DISTRIBUTIONMETHOD_2>
<DIST_CREDITOR_2>WILLIAM HOOK</DIST_CREDITOR_2>
<DIST_AMOUNT_2>1239.86</DIST_AMOUNT_2>
<DIST_NET_2>Yes</DIST_NET_2>
</Distributions>

I need to Sum DIST_AMOUNT_1, 2, etc, up to a possible 15 in total that may or may not exist.

Thusfar, I've assigned each DIST_AMOUNT to a variable after checking to see if it exists. The sum itself is where I'm having issues as there is nothing populating for the sum and I've no idea why, I've beaten my head on this and googled for answers for days now. Any help is appreciated.

My XSL code thusfar:

<xsl:variable name="DIST_TMP_1">
            <xsl:choose>
                <xsl:when test="//DIST_AMOUNT_1">
                    <xsl:value-of select="number(//DIST_AMOUNT_1)"/>
                </xsl:when>
                <xsl:otherwise>
                    <xsl:value-of select="number(0.00)"/>
                </xsl:otherwise>
            </xsl:choose>
        </xsl:variable>
        <xsl:variable name="DIST_TMP_2">
            <xsl:choose>
                <xsl:when test="//DIST_AMOUNT_2">
                    <xsl:value-of select="number(//DIST_AMOUNT_2)"/>
                </xsl:when>                 
                <xsl:otherwise>
                    <xsl:value-of select="number(0.00)"/>
                </xsl:otherwise>
            </xsl:choose>
        </xsl:variable> 
        <xsl:variable name="DIST_TMP_3">
            <xsl:choose>
                <xsl:when test="//DIST_AMOUNT_3">
                    <xsl:value-of select="number(//DIST_AMOUNT_3)"/>
                </xsl:when>                 
                <xsl:otherwise>
                    <xsl:value-of select="number(0.00)"/>
                </xsl:otherwise>
            </xsl:choose>
        </xsl:variable>
        <xsl:element name="ECD070_TOTAL_VAR">
            <xsl:value-of select="sum($DIST_TMP_1+$DIST_TMP_2+DIST_TMP_3)"/>
        </xsl:element>

Upvotes: 1

Views: 54

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 117140

Why can't you simply do:

<xsl:value-of select="sum(/Distributions/*[starts-with(name(), 'DIST_AMOUNT_')])" />

Or, if you must be explicit, do:

<xsl:value-of select="sum((DIST_AMOUNT_1, DIST_AMOUNT_2, DIST_AMOUNT_3, ... DIST_AMOUNT_15))" />

(this is from the context of Distributions). There is no need to test each one of these for existence: non-existing nodes will simply be ignored.

Upvotes: 2

Related Questions