sum() Function |
Converts all nodes in the argument node-set to numbers, and then returns the sum of all of those numbers. If any node in the node-set can't be converted to numbers (passing them to the number() function returns NaN), the sum() function returns NaN.
Inputs
A node-set. Any node in the node-set that is not a number is converted to a number as if it were passed to the number() function, then the numeric values of all of the nodes are summed.
Output
The sum of the numeric values of all of the nodes in the argument node-set. If any node in the argument node-set cannot be converted to a number, the sum() function returns NaN.
Defined in
XPath section 4.4, Number Functions.
Example
We'll demonstrate the sum() function against the following XML document:
    <?xml version="1.0"?>
    <report>
      <title>Miles Flown in 2001</title>
      <month sequence="01">
        <miles-flown>12379</miles-flown>
        <miles-earned>35215</miles-earned>
      </month>
      <month sequence="02">
        <miles-flown>32857</miles-flown>
        <miles-earned>92731</miles-earned>
      </month>
      <month sequence="03">
        <miles-flown>19920</miles-flown>
        <miles-earned>76725</miles-earned>
      </month>
      <month sequence="04">
        <miles-flown>18903</miles-flown>
        <miles-earned>31781</miles-earned>
      </month>
    </report>
Here is a stylesheet that uses the sum() function:
    <?xml version="1.0"?>
    <xsl:stylesheet version="1.0"
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

      <xsl:output method="text"/>

      <xsl:variable name="newline">
    <xsl:text>
    </xsl:text>
      </xsl:variable>

      <xsl:template match="/">
        <xsl:value-of select="$newline"/>
        <xsl:text>A test of the sum() function:</xsl:text>

        <xsl:value-of select="$newline"/>
        <xsl:value-of select="$newline"/>
        <xsl:text>Total miles flown this year:  </xsl:text>
        <xsl:value-of
          select="format-number(sum(/report/month/miles-flown), '###,###')"/>
        <xsl:value-of select="$newline"/>
        <xsl:value-of select="$newline"/>
        <xsl:text>Total miles earned this year: </xsl:text>
        <xsl:value-of
          select="format-number(sum(/report/month/miles-earned), '###,###')"/>
        <xsl:value-of select="$newline"/>
        <xsl:value-of select="$newline"/>
      </xsl:template>

    </xsl:stylesheet>
Processing the XML document with this stylesheet generates these results:
    A test of the sum() function:

    Total miles flown this year:  84,059

    Total miles earned this year: 236,452