Like the title
<test>
<num>1 5 7</num>
<num>4-2</num>
.....
</test>
how to get the sum for each num tag
i have tried to change the string like from {1 5 7} to {1 5 7} then use sum or number function but it did't work
expected get
<test>
<num>13</num>
<num>2</num>
.....
</test>
or other format thx
CodePudding user response:
sum(tokenize(<num>1 5 7</num>)!xs:decimal(.))
gives 13
. It is not clear how the example <num>4-2</num>
and the sum (?) 2
fits in.
CodePudding user response:
Martin Honnen's and Mads Hansen's answers were missing the actual querying and result returning part. I also added some extra lines with useful variable names for readability.
let $data :=
<test>
<num>1 5 7</num>
<num>4-2</num>
</test>
return
<result>{
for $num in $data/num
let $normalized := replace($num/text(), '-', ' -')
let $numbers := tokenize($normalized, ' ') ! number(.)
return
<sum>{sum($numbers)}</sum>
}</result>