XML - XML Namespaces
What is an XML Namespace?
An XML Namespace is a way to avoid element name conflicts when combining XML documents from different sources.
It helps distinguish between elements that have the same name but come from different contexts.
Why Use Namespaces?
Imagine two XML documents:
-
One describes books
-
Another describes software
Both may use a <title>
tag — but the meaning is different. Namespaces help differentiate them.
Syntax of XML Namespace
xmlns:prefix="URI"
-
xmlns
stands for XML Namespace. -
prefix
is a short label (likebk
,sw
). -
URI
is a unique identifier (like a website URL – it doesn’t need to point to an actual file).
Example: XML with Namespaces
<catalog xmlns:bk="http://example.com/books"
xmlns:sw="http://example.com/software">
<bk:item>
<bk:title>XML Made Easy</bk:title>
<bk:author>John Doe</bk:author>
</bk:item>
<sw:item>
<sw:title>Text Editor Pro</sw:title>
<sw:version>5.1</sw:version>
</sw:item>
</catalog>
How it works:
-
bk:title
= Book title -
sw:title
= Software title
Even though both elements are called <title>
, their prefixes (bk, sw) and namespaces make them unique.
Feature | Description |
---|---|
xmlns |
Declares a default or prefixed namespace |
Namespace URI | Uniquely identifies the context |
Prefix | Short label to use in tags |
Avoids Conflicts | Differentiates same-named elements |
Default Namespace (No Prefix)
You can also declare a default namespace without a prefix:
<note xmlns="http://example.com/note">
<to>Alice</to>
<from>Bob</from>
</note>
Here, all elements inside <note>
belong to the same namespace.