XQuery/Updates and Namespaces

Motivation
You want to update an XML file and understand how the XQuery update process might impact the namespace of the document the next time it is viewed.

Method
We will use the XQuery update statement to change the values of XML documents and note how the default output changes with respect to how the default namespaces and namespace prefixes are rendered. XQuery updates can impact how namespaces are rendered.

Example
Suppose we have a task that includes a default namespace like the following XML document.

Example XML document using a default namespace.

In the following example we refer to this XML document as $doc.

Most people that want to view XML prefer to use a default namespace and not clutter the entire document with unnecessary prefixes.

Suppose we have just saved this file and we now want to add an ID value to the  element. After we update this XML file with the following update statement we note that the serialization will change.

update replace $doc/task:task/task:id with 123

The next time we view this document we see the following:

This is known as "fully qualified" document where the namespace prefix of every element is fully shown. It is technically equivalent to the prior example. This may not be what you would like.

Updating the Element Value, not the entire Element
To get around this we can just update the text node of the id instead of the entire id element:

update replace $doc//task:id/text with 123

or you can use the update/value syntax

update value $doc//task:id with 123

Using either of these techniques will not dirty up your default namespace structures.

Acknowledgments
Joe Wicentowski was kind enough to make these observations and provide samples.