Previous | Next | Indexes
Zvon > Tutorials > XSLT 2.0 Tutorial > Arithmetics (4/6) >

Summation

Function sum() sums all values of a sequence. All items of the sequence must be transformable to a numeric value.

If the argument of the sum() function is an empty sequence (in this example there is no element b), "0" is returned if the sum() function does not have a second argument. If the second argument is provided the returned value is equal to this argument.

XSLT

      <xsl:stylesheet
                  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                  version="2.0">
            <xsl:output  method="xml"
                        indent="yes"
                        omit-xml-declaration="yes"/>

            <xsl:template  match="/aaa">
                  <bbb>
                        <xsl:value-of  select="sum(1 to 99)"/>
                  </bbb>
                  <ccc>
                        <xsl:value-of  select="sum(a)"/>
                  </ccc>
                  <ddd>
                        <xsl:value-of  select="sum(b)"/>
                  </ddd>
                  <eee>
                        <xsl:value-of  select="sum(b,100)"/>
                  </eee>
            </xsl:template>

      </xsl:stylesheet>
XML

      <aaa>
            <a>5</a>
            <a>3</a>
            <a>7</a>
            <a>2</a>
      </aaa>
Output

      <bbb>4950</bbb>
      <ccc>17</ccc>
      <ddd>0</ddd>
      <eee>100</eee>


Previous chapter: Implicit behaviour
Next chapter: Functions operating on strings
Previous page: Modulus
Next page: Average