Let expressions

XPath 3.0 allows let expressions, previously available only in XQuery. For example the expression let $x := . return //a[@status=$x] binds the variable $x to the context item, and then evaluates the expression //a[@status=$x] which makes use of this variable.

From XPath 4.0:

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

    for $i in 1 to 9 let $j := $i+1 return $i × $j

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

    This example also demonstrates another new XPath 4.0 feature: the symbols × and ÷ can be used for multiplication and division in place of * and div.

  • The type of variables can be declared in a let expression. (Implemented from Saxon 13.) In both XPath 4.0 and XQuery 4.0, unlike previous XQuery versions, the value is coerced to the required type: so, for example, let $x as xs:double := "1.234" binds $x to the result of casting the string "1.234" to type xs:double.

  • Sequences, arrays, and maps can be destructured to extract their components into multiple variables. (Implemented from Saxon 13.) For example:

    let $[ $x, $y, $z ] := [3, 4, 5] return `x={$x} y={$y} z={$z}`

    returns "x=3 y=4 z=5". The same result is returned by the expression:

    let ${ $x, $y, $z } := {'x':3, 'y':4, 'z':5} return `x={$x} y={$y} z={$z}`