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"

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.

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