Francy Grillo
Francy Grillo

Reputation: 99

XSLT - sum of values of attributes of different nodes

I have this code XML:

<?xml version="1.0" encoding="UTF-8"?>
<!-- Edited by XMLSpy -->
<girone>
    <classifica>
        <squadra nome="Guerrieri" punti="3"/>
        <squadra nome="Indios" punti="5"/>
                <squadra nome="Leoni" punti="4"/>
                <squadra nome="Primula Rossa" punti="1"/>
    </classifica>
    <risultati>
            <partita id="g11">
                     <squadra nome="Indios" goal="2"/>
                     <squadra nome="Guerrieri" goal="0"/>
            </partita>
            <partita id="g12">
                     <squadra nome="Primula Rossa" goal="0"/>
                     <squadra nome="Leoni" goal="3"/>
            </partita>
            <partita id="g13">
                     <squadra nome="Guerrieri" goal="2"/>
                     <squadra nome="Leoni" goal="0"/>
            </partita>
            <partita id="g14">
                     <squadra nome="Indios" goal="1"/>
                     <squadra nome="Primula Rossa" goal="1"/>
            </partita>
            <partita id="g15">
                     <squadra nome="Indios" goal="1"/>
                     <squadra nome="Leoni" goal="1"/>
            </partita>
    </risultati>
</girone>

and this code XSLT (a fragment):

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:for-each select="girone">
    <xsl:for-each select="risultati/partita/squadra[@nome='Indios']">
           <xsl:value-of select="sum(@goal)"/>
    </xsl:for-each>
</xsl:for-each>

I have to sum all the goals scored by the team "Indios". But instead of getting the result: 4, I get: 211. that is not the sum, but the number of goals (corrected) in sequence.

Also, I should to sum goals conceded of the team "Indios". I had thought like so:

<xsl:for-each select="girone">
    <xsl:if test="risultati/partita/squadra[@nome='Indios']">
         <xsl:value-of select="sum(risultati/partita/squadra[@nome!='Indios']/@goal)"/>
    </xsl:if>     
</xsl:for-each>

Upvotes: 1

Views: 1298

Answers (1)

Tim C
Tim C

Reputation: 70638

You don't need the xsl:for-each on the squadra elements here. For sum() to work, just put the xpath expression of the nodes you wish to sum inside the sum() function itself, like so:

<xsl:for-each select="girone">
    <xsl:value-of select="sum(risultati/partita/squadra[@nome='Indios']/@goal)"/>
</xsl:for-each>

This should give you the answer 4.

EDIT: If you want the goals conceded by 'Indios' in games they have played, the expression will be as follows:

<xsl:value-of select="sum(risultati/partita[squadra[@nome='Indios']]/squadra[@nome!='Indios']/@goal)"/>

This gives the result 2.

Upvotes: 3

Related Questions