I like to manipulate an XML file using some queries. I want to add some attributes to the existing nodes if they don't possess it before or during the execution of the query.
for example:
// if there is a price and the parents don't have
// the attribute named hasPrice then add it to them
<products hasPrice='yes' >
<item hasPrice='yes'>
<price>100 </price>
</item>
<item hasPrice='yes'>
<price>100 </price>
</item>
</products>
I tried the following XQuery but it says Duplicate attribute hasPrice
declare function local:propagatePrice($x)
{
copy $t := $x
modify (
for $y in $t//price,
$z in $y/ancestor::*
return if ($z/@hasPrice) then ()
else (insert node (attribute { 'hasPrice' } {'yes'}) into $z)
)
return $t
};
let $db := doc('products.xq')
let $temp := local:propagatePrice($db)
return $temp
I am not quite sure to understand what difficulty you found. What you try to achieve is certainly possible with XQuery (or with XSLT, which is more convenient for transforming XML trees, especially for multiple transform passes).
In XQuery, you can manipulate some XML trees in memory, so if you have your "transform" logic in 2 functions, then you can "chain" them like this:
or more succinctly: