For expressions

The expression for $x in E1 return E2 returns the sequence that results from evaluating E2 once for every item in the sequence E1. Note that E2 must use the range variable $x to refer to the item being tested; it does not become the context item. For example, sum(for $v in order-item return $v/price * $v/quantity) returns the total value of (price times quantity) for all the selected order-item elements.

XPath 4.0 supports a larger subset of the XQuery FLWOR expression syntax:

  • Multiple for and let clauses are allowed to be combined in an expression. For example:

    for $i in 0 to 9 let $ii := $i+1 for $j in 1 to 3 return $i * $j

    (The use of multiple for clauses is implemented from Saxon 12.3; while combining with let clauses is implemented from Saxon 13.)

  • Positional variables can be defined. For example:

    for $str at $n in ("red", "green", "blue") return `{$n}:{$str}`

    returns the sequence ("1:red", "2:green", "3:blue"). (Implemented from Saxon 13.)

  • The type of variables can be declared in a for expression:

    for $str as xs:string in (<a>red</a>, <a>green</a>, <a>blue</a>) return $str

    returns the sequence ("red", "green", "blue"). In both XPath 4.0 and XQuery 4.0, unlike earlier XQuery versions, the supplied values are coerced to the declared type. In this example, the elements are atomized to extract their content. (Implemented from Saxon 13.)

For member expressions

A for member expression allows convenient iterative processing of the members of an array. Note that the result of the expression is a sequence, not an array.

Examples:

for member $m in [(3,5,6), (8,12)] return sum($m)

returns the sequence (14, 20).

let $json := '[{"x":1, "y":"one"}, {"x":2, "y":"two"}]' return for member $map in parse-json($json) return $map?y

returns ("one", "two").

let $json := '[[1,2,3], [4,5,6]]' return for member $A in parse-json($json), $a in $A return $a*2

returns (2, 4, 6, 8, 10, 12).

For key/value expressions

A for key/value expression allows iteration over the entries in a map. For example:

for key $key value $value in { "x": 1, "y": 2, "z": 3 } return `{$key}={$value}`

returns ("x=1", "y=2", "z=3").

This example also makes use of string templates, another new feature in XPath 4.0.