Reputation: 67
let $a := <product>
<p1>100</p1>
<p2>100</p2>
<p3/>
</product>
for $i in $a
return $i/p1 + $i/p2 + $i/p3
Why do i get invalid lexical value here when i expect the sum to be displayed?
Upvotes: 1
Views: 1403
Reputation: 4241
Your last line return $i/p1 + $i/p2 + $i/p3
is evaluated as return xs:double($i/p1) + xs:double($i/p2) + xs:double($i/p3)
. This works for p1
and p2
, but not p3
:
xs:double($i/p3) = xs:double(<p3/>)
= xs:double(xs:untypedAtomic('')) (: atomization :)
= xs:double('')
Since +
returns the empty sequence ()
if one of its arguments is the empty sequence, your approach would not have worked either way. You can use fn:sum($sequence)
instead, summing over the text nodes inside the elements:
let $a :=
<product>
<p1>100</p1>
<p2>100</p2>
<p3/>
</product>
for $i in $a
return sum(($i/p1/text(), $i/p2/text(), $i/p3/text()))
The last line can even be shortened to:
return sum($i/(p1, p2, p3)/text())
Upvotes: 2