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 $i in 0 to 9 let $ii := $i+1 for $j in 1 to 3 return $i * $jforandletclauses are allowed to be combined in an expression. For example:(The use of multiple
forclauses is implemented from Saxon 12.3; while combining withletclauses 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 $str as xs:string in (<a>red</a>, <a>green</a>, <a>blue</a>) return $strforexpression: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).
returns ("one", "two").
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:
returns ("x=1", "y=2", "z=3").
This example also makes use of string templates, another new feature in XPath 4.0.