Namespaces in XML lets a document combine vocabularies without their names clashing, by giving element and attribute names a namespace identified by a URI. It is a layer on top of XML: a namespace error does not make a document ill-formed XML, but it is not namespace-well-formed.
Declaring and using namespaces
A namespace is declared with an attribute: xmlns:prefix="uri" binds
a prefix, and xmlns="uri" sets the default namespace. The declaration
applies to the element it is on and everything inside it, until overridden. The
declared value is a URI reference; it is only ever compared, never fetched.
A name is a QName: either local or prefix:local, each part an
NCName (a Name with no colon).
| Name | Namespace |
|---|---|
| Element with a prefix | The namespace bound to the prefix |
| Element without a prefix | The default namespace in scope, if any; otherwise no namespace |
| Attribute with a prefix | The namespace bound to the prefix |
| Attribute without a prefix | No namespace, ever: the default namespace does not apply to attributes |
xmlns="" undeclares the default namespace. Prefixes cannot be undeclared
in Namespaces 1.0.
Reserved prefixes and names
- The prefix
xmlis bound tohttp://www.w3.org/XML/1998/namespace. It may be declared, but only to that URI, and no other prefix may use that URI. - The prefix
xmlnsis bound tohttp://www.w3.org/2000/xmlns/and may not be declared; no element or attribute name may use it, and no other prefix may use that URI. - Prefixes beginning with
xmlin any case are reserved.
Namespace constraints
| Constraint | Rule |
|---|---|
| Reserved Prefixes and Namespace Names | As above |
| Prefix Declared | A prefix used in a name must be declared in the element’s scope |
| No Prefix Undeclaring | xmlns:p="" is not allowed in Namespaces 1.0 |
| Attributes Unique (6.3) | No two attributes on an element may have the same expanded name, for example a:v and b:v with both prefixes bound to one URI |
A namespace-well-formed document also has no colon in entity names, PI targets or notation names, and only QNames as element and attribute names. Conformance with namespaces is usually what programs check.
Namespaces in XML 1.1
Namespaces 1.1 applies to XML 1.1
documents. It differs in two ways: namespace names are IRIs rather than URIs, and
a prefix may be undeclared with xmlns:p="", removing its binding for
that element and those inside it.