Re: [xsl] XSLT 1.0 newbie: sum of selected elements

Subject: Re: [xsl] XSLT 1.0 newbie: sum of selected elements
From: "Andrew Welch" <andrew.j.welch@xxxxxxxxx>
Date: Mon, 11 Dec 2006 13:50:31 +0000
On 12/11/06, Kirov Plamen <pkirov@xxxxxxxxx> wrote:
Hello,

I'm trying to sum the selected values from xml, using xsl with Xalan:

XML:

<root>
        <element>
                <type id=1 des="a"/>
                <amount due=10.12 init=0.25/>
        </element>
        <element>
                <type id=2 des="a"/>
                <amount due=1.82 init=1.00/>
        </element>
        <element>
                <type id=1 des="a"/>
                <amount due=-12.00 init=0.00/>
        </element>
        <element>
                <type id=3 des="a"/>
                <amount due=50.00 init=120.35/>
        </element>
</root>


I want to sum @due only for @id=2 or 3


XSL:

<xsl:value-of select="sum(..//element[type/@id = 2 or type/@id =
3]/amount/@due)"/>


If I want to sum by more than 5 different Id's or/and for more amount values(@due, @init...), this method of sorting values is unusual - a lot of repeated "or" clauses for every "select". Is't possible, for this example, elements with @id 2 or 3 to be selected first and after to be summarized @due and/or @init?

You can use a variable to hold the first selection:


<xsl:variable name="elems" select="element[type/@id = 1 or type/@id = 2"/>

Then use sum() on the variable:

<xsl:value-of select="sum($elems/amount/@due)"/>
or
<xsl:value-of select="sum($elems/amount/@init)"/>

By the way, you really should take the time to post well-formed XML
for your sample input -  especially if you would like someone to take
the time to answer you.

cheers
andrew

Current Thread