How to Declare XML Namespaces and Bind URIs
XML namespaces are mechanisms used to prevent element and attribute name collisions by grouping related markup vocabulary under unique identifiers. This article explains the syntax for declaring namespace prefixes, the process of binding them to Uniform Resource Identifiers (URIs), the distinction between default and prefixed namespaces, and how scoping rules apply within an XML document.
Syntax for Declaring a Namespace Prefix
An XML namespace prefix is declared using a reserved attribute syntax
starting with xmlns. The general declaration format inside
an element’s opening tag is:
xmlns:prefix="URI"xmlns: The reserved attribute name designating a namespace declaration.:prefix: The local shorthand name (prefix) assigned to the namespace.URI: A unique string, typically a Uniform Resource Identifier (URN or URL), acting as the global identifier for that namespace.
For example, to associate the prefix bk with the
namespace identifier https://example.com/books:
<bookstore xmlns:bk="https://example.com/books">
<bk:title>XML Developer's Guide</bk:title>
<bk:author>Jane Doe</bk:author>
</bookstore>In this example, every element prefixed with bk: (such
as <bk:title>) is bound to the
https://example.com/books namespace.
Binding Prefixes to URIs
The XML parser associates the defined prefix with the specified URI throughout the element’s subtree.
- The URI as an Identifier: The URI does not need to point to an active website or downloadable schema; it serves purely as a unique identifier string.
- Universal Name Resolution: When a parser encounters
<bk:title>, it resolves the qualified name (QName) into an expanded name consisting of the URI and the local name:{https://example.com/books}title. This distinguishes it from a<lib:title>element bound to{https://example.com/library}title.
Declaring Default Namespaces
A namespace can also be declared without a prefix. This sets a default namespace for the element and all child elements that do not have explicit prefixes:
<store xmlns="https://example.com/ecommerce">
<item>Laptop</item>
</store>Here, <store> and <item> belong
to the https://example.com/ecommerce namespace without
requiring a prefix tag.
Scope of Namespace Declarations
- Hierarchical Scope: A namespace declaration is active on the element where it is declared and all of that element’s descendants.
- Overriding Namespaces: A child element can override
an existing prefix or default namespace by redeclaring the same prefix
or
xmlnsattribute with a different URI. - Root vs. Local Declaration: Declaring namespaces on the root element gives global availability across the entire document, which is standard practice for performance and readability. Local declarations limit the scope to specific subtrees.