Unbind or Redeclare XML Namespace Prefixes
In XML, managing namespace scopes is essential for avoiding name collisions and processing structured documents correctly. This article explains whether a namespace prefix can be redeclared to point to a new URI or completely unbound within a sub-element tree, outlining the rules and behavioral differences between the XML 1.0 and XML 1.1 specifications.
Redeclaring a Namespace Prefix
Yes, an XML namespace prefix can be redeclared at any point in a sub-element tree.
When a child element declares an existing prefix with a new Uniform Resource Identifier (URI), the new binding overrides the parent’s binding. This new association applies exclusively to that child element and all of its descendants, leaving sibling or ancestor elements unaffected.
<root xmlns:ns="http://example.com/v1">
<ns:item>Uses v1 namespace</ns:item>
<!-- Redeclaration on a sub-element -->
<child xmlns:ns="http://example.com/v2">
<ns:item>Uses v2 namespace</ns:item>
</child>
<ns:item>Reverts back to v1 namespace scope</ns:item>
</root>Unbinding the Default Namespace
The default namespace (declared without a prefix using
xmlns="...") can be unbound in both XML 1.0 and XML
1.1.
Setting xmlns="" on a sub-element removes the default
namespace binding for that element and its descendants, placing them
back into no namespace.
<root xmlns="http://example.com/default">
<item>Belongs to http://example.com/default</item>
<!-- Unbinding default namespace -->
<child xmlns="">
<item>Belongs to no namespace</item>
</child>
</root>Unbinding a Prefixed Namespace
The ability to unbind a prefixed namespace depends directly on the XML specification version being used:
- XML 1.0: Prefix unbinding is not
permitted. Setting an empty URI on a prefix declaration (such
as
xmlns:ns="") is considered an error, and compliant XML 1.0 parsers will reject the document. Once a prefix is defined, it can be redeclared to a different URI in child nodes, but it cannot be completely removed from scope. - XML 1.1: Prefix unbinding is
permitted. XML 1.1 introduced the ability to undeclare
prefixes by assigning an empty string to the namespace attribute
(
xmlns:ns=""). Inside that sub-element tree, the prefixnsis no longer bound to any URI, and attempting to use<ns:item>without re-declaring it will throw an error.
<!-- Valid in XML 1.1, Invalid in XML 1.0 -->
<root xmlns:ns="http://example.com/ns">
<ns:item>Valid prefix</ns:item>
<child xmlns:ns="">
<!-- 'ns' is now unbound in this subtree -->
<item>Valid standard element</item>
</child>
</root>