XPath operator
Arithmetic + - * div mod
Division is div, not / — because / is the path separator. There is no string concatenation operator.
XPath's arithmetic operators are +, -, *, div and mod. Division is spelled out because / already means 'child step', and mod is spelled out for symmetry.
The - operator needs care: XML names may contain hyphens, so `qty-1` is a name test, not a subtraction. Put spaces around it.
- Syntax
number div number- Returns
- number
- Kind
- Operator
- Version
- XPath 1.0 (libxml2)
Worked examples
Each result below is what the evaluator returned, asserted on every test run. An empty result means an empty node-set — which is an answer, not an error.
sum(//price) div count(//price)on order.xmlRun17.8333XPath 1.0 numbers are IEEE doubles, and libxml2 prints them at its own precision rather than in full.
7 mod 3on order.xmlRun1round(sum(//price) div count(//price) * 100) div 100on order.xmlRun17.83An average to two places — there is no avg() and no rounding precision argument.
2 * 3 + 1on order.xmlRun7
What catches people out
- Use div, never /. A / in an arithmetic position is a path step and will not parse as you meant.
- Write `a - b` with spaces. Without them, a-b is a valid XML name and will be read as one.
- 'a' + 'b' is arithmetic on two non-numbers, so it is NaN — not concatenation. Use concat().
- Division by zero gives Infinity rather than an error.
The sample documents
Every example on this page runs against this document. The sitemap one is namespaced on purpose — almost every real XML document is, and that changes which expressions match.
<?xml version="1.0" encoding="UTF-8"?>
<order id="A-1001" tier="gold">
<customer country="NO">Ada Lovelace</customer>
<lines>
<line sku="WIDGET-1" qty="2"><price>14.50</price></line>
<line sku="WIDGET-2" qty="1"><price>39.00</price></line>
<line sku="GIFT-WRAP" qty="1"><price>0.00</price></line>
</lines>
<note> Deliver after 09:00 </note>
</order>Related
- number()Converts to a number, producing NaN rather than an error when it cannot — which is how bad data passes silently.
- sum()Adds the numeric values of every node in a set. One non-numeric node makes the whole result NaN.
- round(), floor() and ceiling()The three rounding functions. round() goes to the nearest integer, breaking ties upward — including for negatives.
- concat()Joins two or more strings. There is no + for strings in XPath.
Get started
Bring order to the XML your team can't afford to ignore.
Create a free account and get a private workspace to search, validate, diff, and monitor your XML feeds, sitemaps, schemas, and vendor integrations.