XML Attributes and Default Namespaces Explained
In XML, default namespaces apply exclusively to elements and are not inherited by attributes. While an unqualified element inherits the default namespace declared on itself or an ancestor, an unqualified attribute always belongs to no namespace at all. Understanding this distinction is essential for correctly querying, validating, and processing XML documents that utilize namespaces.
The Rule: Default Namespaces Apply Only to Elements
A default namespace is declared using the xmlns
attribute without a prefix (for example,
xmlns="http://example.com/ns"). According to the W3C XML
Namespaces specification, this declaration sets the namespace for the
element on which it appears and all of its descendant elements that do
not explicitly declare their own namespace.
However, default namespaces do not apply to attributes. An attribute without a namespace prefix is never in the default namespace; it is in “no namespace” (also known as the null or unqualified namespace).
Example of Attribute Behavior
Consider the following XML snippet:
<person xmlns="http://example.com/ns" id="101" status="active">
<name>Jane Doe</name>
</person>In this example: * The <person> element is in the
http://example.com/ns namespace. * The
<name> element inherits the default namespace and is
also in the http://example.com/ns namespace. * The
id and status attributes are in no
namespace, despite being declared directly on an element with a
default namespace.
How to Place an Attribute in a Namespace
To assign an attribute to a specific namespace, you must explicitly use a prefixed namespace declaration.
<person xmlns="http://example.com/ns"
xmlns:meta="http://example.com/meta"
id="101"
meta:status="active">
<name>Jane Doe</name>
</person>In this case: * id remains in no namespace. *
meta:status is explicitly placed in the
http://example.com/meta namespace via the meta
prefix.
Why This Rule Exists
The W3C specification designed attribute scoping this way because
attributes already derive their context directly from the element to
which they belong. An attribute named id on a
<person> element is inherently interpreted as the
identifier of that specific person. Automatically putting attributes
into the default namespace would create unnecessary complexity and
ambiguity when integrating different schemas and parsing documents with
technologies like XPath or XSLT.
Implications for XPath and Processing
When querying XML documents with tools like XPath, you must treat unprefixed attributes as having no namespace:
- To select the element in the example:
/ns:person(wherensis bound tohttp://example.com/nsin your processor). - To select the unprefixed attribute:
/ns:person/@id(the attribute selector@iduses no prefix). - To select the prefixed attribute:
/ns:person/@meta:status(wheremetais bound tohttp://example.com/meta).