--- title: "sum()" description: "Returns the sum of the numeric values in a node-set or sequence, or a specified zero value for empty sequences." date: 2026-04-18T00:00:00Z version: "1.0" versionLabel: "XSLT 1.0" category: "numeric function" syntax: "sum(node-set)" tags: ["xslt", "reference", "xslt1", "xpath"] --- ## Description `sum()` converts each node in a node-set to a number (using the XPath `number()` rules) and returns their total as a double. If any node cannot be converted to a number, its value is treated as `NaN`, and the entire result is `NaN`. In XSLT 2.0+, `sum()` accepts any sequence of atomic values that can be added together. A second argument may be provided as a **zero value** to return when the sequence is empty (in XPath 1.0, `sum()` on an empty node-set returns `0`). `sum()` is the standard way to compute totals over repeated elements, such as order amounts, quantities, or scores, without writing an explicit loop. ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `node-set` | node-set / sequence | Yes | The nodes or items to sum. Each is converted to a number. | | `zero` | atomic value | No | Value to return if the sequence is empty (XPath 2.0+). Defaults to `0`. | ## Return value `xs:double` (XPath 1.0) or the type matching the input sequence (XPath 2.0+) — the numeric sum of all items. ## Examples ### Sum all child element values **Input XML:** ```xml ``` **Stylesheet:** ```xml Total: ``` **Output:** ``` Total: 49.49 ``` ### Conditional sum (sum filtered values) **Input XML:** ```xml ``` **Stylesheet:** ```xml ``` **Output:** ```xml 275 330 ``` ### Empty sequence with fallback (XSLT 2.0) ```xml ``` ## Notes - Nodes that cannot be converted to a number (e.g., text like `"N/A"`) produce `NaN`, which propagates through the sum. Validate data or use `number()` with a fallback before summing. - `sum()` on an empty node-set returns `0` in XPath 1.0. In XPath 2.0+, the second argument controls this behaviour. - For an average, there is no built-in `avg()` in XPath 1.0. Compute it as `sum(nodes) div count(nodes)`. XPath 2.0+ provides `avg()`. - `sum()` works on attribute nodes as well as element text nodes; the path `sum(items/item/@qty)` is valid. ## See also - [count()](../xpath-count)