1
votes

How can I rename all foo tags as baz using an XQuery as below?

FLWOR:

declare namespace map = "http://www.w3.org/2005/xpath-functions/map";
declare namespace array = "http://www.w3.org/2005/xpath-functions/array";

declare namespace output = "http://www.w3.org/2010/xslt-xquery-serialization";

for $x in /root

return rename node $x/root/foo as "baz"

Sample doc:

  <root>
    <foo>bar</foo>
  </root>

output I'm looking for:

  <root>
    <baz>bar</baz>
  </root>

see also:

http://xqueryfiddle.liberty-development.net/nc4P6y8

and:

removing an element from xml using saxon xquery

which uses something not entirely dissimilar..

2
Which edition of Saxon do you use? The XQuery fiddle uses Saxon HE where there is no support for XQuery update.Martin Honnen

2 Answers

3
votes

Assuming your real document is more complex than the one shown, making small changes to a big document is generally easier using XSLT rather than XQuery. In XSLT 3.0 this is

<xsl:stylesheet ...>
  <xsl:mode on-no-match="shallow-copy"/>
  <xsl:template match="foo">
    <baz><xsl:apply-templates/></baz>
  </xsl:template>
</xsl:stylesheet>

Alternatively if this is a one-off requirement, consider using Saxon's Gizmo utility:

java net.sf.saxon.Gizmo -s:source.xml
/>rename //foo to "baz"
/>save out.xml
/>quit
3
votes

You should be able to use

for $foo in doc('input.xml')//foo
return rename node $foo as "baz"

assuming you have support for XQuery update (like in Saxon 9 or 10 EE or in BaseX).