(:~
: Adds namespace nodes to a node, retaining its base URI.
: Note that the namespaces are added to the root element of
: the incoming document or fragment.
:)
declare function f:addNamespaces($node as node(),
$namespaces as namespace-node()*)
as node() {
let $root := $node ! root()
let $fnElem := function($n) {$n/descendant-or-self::*[1]}
let $prefixes := $namespaces ! name(.)
let $uris := $namespaces ! string(.)
return $root
update {
for $p at $pos in $prefixes
let $uri := $uris[$pos]
let $attName := QName($uri, $p||':_')
return insert node attribute {$attName} {()} into $fnElem(.)
}
update {
let $elem := $fnElem(.)
for $p in $prefixes
return delete node $elem/@*[name() eq $p||':_']
}
};