Change namespace in XQuery

2.6k Views Asked by At

I found the following XQuery user-defined function in the O'Reiily book XQuery and it is used to change the namespace of an XML file when it is printed:

declare namespace functx = "http://www.functx.com";
declare function functx:change-element-ns-deep
($element as element(), $newns as xs:string) as element()
{
let $newName := QName ($newns, name ($element))
return (element {$newName} 
      {$element/@*,
       for $child in $element/node()
       return if ($child instance of element())
              then functx:change-element-ns-deep ($child, $newns)
              else $child
       }
      )
};

One example to call this function with is:

<text xmlns:pre="pre"> 
{           
  functx:change-element-ns-deep(<pre:x><pre:y>123</pre:y></pre:x>, "http://new") 
}  
</text> 

returns:

<test xmlns:pre="pre" > 
  < x xmlns="http//new">  
    <y>123</y> 
  </x>   
</test> 

But what I've got is:

<test>  
  <x>    
    <y>123</y>  
  </x>  
</test>

It appears that the original namespace is stripped but the new one has yet to be attached or is it simply that the processor doesn't print the namespace because the unaffected namespace declaration is also gone?

2

There are 2 best solutions below

1
On

The eXist Sandbox results window unfortunately does not display namespace attributes (@xmlns). But if you save your query as an .xq file and run it via your browser, you'll see it actually is preserving the namespace information properly. By the way, the next generation version of the Sandbox, called eXide, does display namespace info somewhat better. See the demo of eXide at https://exist-db.org/exist/apps/eXide.

0
On

I have got a similar issue using a Saxon 9.3 implementation on OSB 11. Strangely it works on Oxygen but it doesn't on OSB.