Namespaces in XML
Namespaces in XML
What is an XML Namespace?
An XML Namespace is a way to avoid element name conflicts when combining XML documents from different XML vocabularies.
It provides uniqueness by qualifying element and attribute names with a URI (Uniform Resource Identifier).
Why Use Namespaces?
Different XML documents or standards may use the same element names.
Namespaces prevent ambiguity by distinguishing elements that have the same name but different meanings.
How Namespaces Work
A namespace is declared using an attribute called
xmlns(XML namespace).The value of
xmlnsis a URI (doesn't have to be a real URL) that uniquely identifies the namespace.
Declaring a Namespace
Default Namespace (for elements)
<book xmlns="http://example.com/book"> <title>XML Basics</title></book>All elements inside
<book>belong to the namespace"http://example.com/book".
Namespace with Prefix
<bk:book xmlns:bk="http://example.com/book"> <bk:title>XML Basics</bk:title></bk:book>bkis the prefix bound to the namespace URI.Elements prefixed with
bk:belong to that namespace.
Using Multiple Namespaces
<root xmlns:bk="http://example.com/book" xmlns:auth="http://example.com/author"> <bk:book> <bk:title>XML Guide</bk:title> </bk:book> <auth:author> <auth:name>Jane Doe</auth:name> </auth:author></root>Different prefixes distinguish elements from different vocabularies.
Attributes and Namespaces
Attributes do not inherit the default namespace.
Attributes can also have prefixes if needed.
<book xmlns="http://example.com/book" bk:id="123"> <title>XML Basics</title></book>Here, bk:id is in the namespace bound to prefix bk.
Summary
| Concept | Description |
|---|---|
| Namespace | Unique identifier (URI) for XML elements |
| Purpose | Avoid naming conflicts |
| Declared with | xmlns or xmlns:prefix |
| Prefix | Short name to refer to a namespace |
| Default Namespace | Applied to elements without prefix |
| Multiple Namespaces | Possible with different prefixes |
If you want, I can provide example XML documents using namespaces or explain how to use them in your XML processing code!