cis
cis

Reputation: 1377

Access variable from within itself in XQuery

I'm wondering whether in XQuery it is possible to access some elements in a variable from within the variable itself.

For instance, if you have a variable with several numbers and you want to sum them all up inside the variable itself. Can you do that with only one variable? Consider something like this:

 let $my_variable := 
      <my_variable_root>
        <number>5</number>
        <number>10</number>
        <sum>{sum (??)}</sum>
      </my_variable_root>
return $my_variable

Can you put some XPath expression inside sum() to access the value of the preceding number elements? I've tried $my_variable//number/number(text()), //number/number(text()), and preceding-sibling::number/number(text()) - but nothing worked for me.

Upvotes: 0

Views: 92

Answers (2)

BeniBela
BeniBela

Reputation: 16917

You cannot do that. The variable is not created, till everything in it is constructed.

But you can have temporary variables in the variable

Like

let $my_variable := 
  <my_variable_root>{
    let $numbers := (
      <number>5</number>,
      <number>10</number>
    )
    return ($numbers, <sum>{sum ($numbers)}</sum>)
  } </my_variable_root>

Or (XQuery 3):

let $my_variable := 
  <my_variable_root>{
    let $numbers := (5,10) 
    return (
      $numbers ! <number>{.}</number>, 
      <sum>{sum ($numbers)}</sum>)
  } </my_variable_root>

Upvotes: 3

Jens Erat
Jens Erat

Reputation: 38712

This is not possible, neither by using the variable name (it is not defined yet), nor using the preceding-sibling axis (no context item bound).

Construct the variable's contents in a flwor-expression instead:

let $my_variable := 
     let $numbers := (
       <number>5</number>,
       <number>10</number>
     )
     return
      <my_variable_root>
        { $numbers }
        <sum>{ sum( $numbers) }</sum>
      </my_variable_root>
return $my_variable

If you have similar patterns multiple times, consider writing a function; using XQuery Update might also be an alternative (but does not seem to be the most reasonable one to me, both in terms of readability and probably performance).

Upvotes: 3

Related Questions