Im using BaseX, which implements XQuery 3.0.
How do I embellish an XML datasource in XQuery, without having to type out all the elements that I want to include? For example, consider the following XML:
<X>
<name>The root</name>
<Y>
<name> Level 1</name>
<Z>
<name>Level 2a</name>
<value>1</value>
</Z>
</Y>
<Y>
<name>Level 1b</name>
<Z>
<name>Level 2b</name>
<value>2</value>
</Z>
</Y>
</X>
I want to add the sum of all values on each level, like this:
<X>
<name>The root</name>
<value>3</value>
<Y>
<name> Level 1</name>
<value>1</value>
<Z>
<name>Level 2a</name>
<value>1</value>
</Z>
</Y>
<Y>
<name>Level 1b</name>
<value>2</value>
<Z>
<name>Level 2b</name>
<value>2</value>
</Z>
</Y>
</X>
I can use an XQuery like this for this:
for $x in /X
return
<X>{
$x/name,
<value>{sum($x//value)}</value>,
for $y in $x/Y
return
<Y>{
$y/name,
<value>{sum($y//value)}</value>,
$y/Z
}</Y>
}</X>
But this gets tedious very fast, when I have a lot of elements that I have to repeat. Is there a way to get this result without having to type out all the attributes and elements I want to preserve in the result set?