Skip to main content
XMLDir

Search 169 pages — formats, namespaces, parser messages, schema errors and tools.

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.xmlRun
    17.8333

    XPath 1.0 numbers are IEEE doubles, and libxml2 prints them at its own precision rather than in full.

  • 7 mod 3on order.xmlRun
    1
  • round(sum(//price) div count(//price) * 100) div 100on order.xmlRun
    17.83

    An average to two places — there is no avg() and no rounding precision argument.

  • 2 * 3 + 1on order.xmlRun
    7

Run your own expression

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.

order.xml
<?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

All 34 XPath entries

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.