XPath Reference

XPath 2.0+ / 3.1

XPath 2.0 and 3.1 are a different language in scale: real conditional and iteration constructs, regular expressions, sequence joins and quantifiers, and the arrow operator for fluent chaining. If you're stuck composing something awkward in XPath 1.0, there's a good chance the modern spec has a one-liner for it. Toggle the engine to 3.1 to try these.

for $x in expr return expr

Iterate and transform

The 'for' expression iterates over a sequence and returns a new sequence built from each item. It's similar to map() in functional programming. For example, you can iterate over ingredients and extract just their amounts, or transform a set of nodes into computed values.

if (cond) then a else b

Conditional expression

A conditional expression that returns one of two values based on a boolean test. Unlike predicates which filter nodes, if/then/else produces a value. It's essential for data transformation — for example, categorizing items or providing default values when data is missing.

some $x in S satisfies P

Existential quantifier

Returns true if at least one item in the sequence satisfies the predicate. It's like an 'any' or 'exists' check. For example, you can test whether any ingredient in a recipe contains a specific allergen, without needing to check each one individually.

every $x in S satisfies P

Universal quantifier

Returns true only if every item in the sequence satisfies the predicate. It's the stricter cousin of 'some' — useful for validation. For example, checking that all steps in a recipe have an order attribute, or that every ingredient has an amount specified.

matches(str, regex)

Regex matching (2.0+)

Tests whether a string matches a regular expression pattern. Unlike contains() which only checks for literal substrings, matches() supports full regex syntax including character classes, quantifiers, and alternation. It brings powerful text matching to XPath.

replace(str, regex, rep)

Regex replacement (2.0+)

Replaces parts of a string that match a regex pattern with a replacement string. The replacement can use $1, $2, etc. for captured groups. This is far more powerful than translate() — you can do complex text transformations within XPath itself.

tokenize(str, regex)

Split string by regex (2.0+)

Splits a string into a sequence of substrings using a regex as the delimiter. This is XPath's string split function. For example, you could split a comma-separated list into individual items, or break a sentence into words by splitting on whitespace.

string-join(seq, sep)

Join sequence with separator

Joins a sequence of strings into a single string with a separator between each item. It's the inverse of tokenize(). This is perfect for building readable output from multiple nodes — like joining all ingredient names with commas.

abs(n), min(seq), max(seq)

Numeric functions (2.0+)

XPath 2.0 added many numeric functions beyond the 1.0 basics. abs() returns the absolute value, min() and max() find the smallest and largest values in a sequence. These are essential for data analysis — finding extremes, normalizing values, or computing ranges.

map { k: v }

Map constructor (3.1)

Creates an inline map (key-value structure) in XPath 3.1. Maps are useful for building structured data, lookup tables, or returning multiple named values from an expression. Keys can be any atomic type and values can be anything including other maps or arrays.

array { items }

Array constructor (3.1)

Creates an array — an ordered collection that, unlike sequences, can contain nested sequences as individual members. Arrays in XPath 3.1 are useful when you need to preserve grouping structure, as sequences in XPath are always flat.

?key or ?(pos)

Map/array lookup operator (3.1)

The ? operator accesses map entries by key or array entries by position. For maps, ?name retrieves the value for key 'name'. For arrays, ?1 retrieves the first member. This provides concise syntax for navigating structured data built with map and array constructors.

=>

Arrow operator for chaining (3.1)

The arrow operator passes the left-hand value as the first argument to the right-hand function, enabling a fluent chaining style. Instead of writing normalize-space(upper-case($x)), you can write $x => upper-case() => normalize-space(). This makes complex transformations more readable.

matches(str, regex, flags)

Regex test with flags (3.1)

The three-argument form of matches() accepts regex flags: 'i' for case-insensitive, 'm' for multi-line, 's' for dot-matches-newline, 'x' for ignore-whitespace, and 'q' for literal (no metacharacters). Handy when you want a case-insensitive contains-style check without lowercasing both sides yourself.

contains-token(str, tok)

Whitespace-token membership (3.1)

Returns true when the token appears as a whitespace-separated word in the string — the same semantics CSS uses for class attributes. Avoids the classic contains(@class, 'btn') false positive where 'btn-primary' also matches.

parse-xml(str)

Parse an XML string (3.1)

Parses an XML string into a document node you can then navigate with XPath. Useful when XML is embedded as a string inside an attribute, a CDATA section, or fetched from elsewhere. The companion parse-xml-fragment() allows multiple top-level nodes.

parse-xml-fragment(str)

Parse an XML fragment (3.1)

Like parse-xml() but doesn't require a single root element. Use it when the string contains a fragment such as several sibling elements or just text — for example, a snippet of mixed markup pulled from another field.

serialize(node)

Serialize a node to XML (3.1)

Turns a node (or sequence of nodes) back into its XML string form. The inverse of parse-xml(). Useful for previewing matched sub-trees, building strings to compare against, or piping XPath results into something that expects text.

parse-json(str)

Parse a JSON string (3.1)

Parses a JSON string into XPath's map/array types. Objects become maps, arrays become arrays, and you can navigate the result with the ? lookup operator (e.g. parse-json('…')?items?1?name). Bridges JSON data into the XPath world.

parse-ietf-date(str)

Parse an RFC-style date (3.1)

Parses dates in the formats commonly seen in HTTP headers and email — for example 'Wed, 06 Jun 1994 07:29:35 GMT' — into an xs:dateTime. Spares you from writing custom string-slicing for legacy date formats.

format-integer(n, picture)

Format an integer (3.1)

Formats an integer using a picture string: '1' for decimal, '001' for zero-padded, 'I' for upper-case Roman numerals, 'i' for lower-case Roman, 'A'/'a' for alphabetic. Picture-string formatting for dates and arbitrary numbers is intentionally not enabled here — see the FAQ.

random-number-generator()

Random number generator (3.1)

Returns a map with a 'number' field (a random double in [0,1)), a 'next' field (a function producing the next generator), and a 'permute' function (which shuffles a sequence). Deterministic and stateless — repeated calls without using ?next yield the same number.

math:*

pi, sqrt, pow, log, exp, sin/cos/tan, atan2 (3.1)

XPath 3.1 ships a math:* namespace with the usual scientific helpers: math:pi(), math:sqrt(n), math:pow(b, e), math:exp(n), math:log(n), math:log10(n), and the trig family math:sin/cos/tan/asin/acos/atan/atan2. Combine with arithmetic operators for real numeric work.

array:*

sort, flatten, for-each, filter, size, reverse (3.1)

Arrays in XPath 3.1 come with their own helpers in the array:* namespace, including array:sort(), array:flatten() (unwraps nested arrays into a sequence), array:for-each() (mapping over members), array:filter(), array:size(), array:reverse(), and array:join() (concatenating arrays).

← Back to full reference