XML Namespaces
XML namespaces prevent element and attribute names from colliding when documents combine vocabularies from more than one source.
The Name Collision Problem
Because anyone can invent XML element names, two documents can easily use the same tag name to mean two different things. A <table> element might mean a piece of furniture in one document and a set of rows and columns of data in another. Combine both inside a single XML document, and a parser has no way to tell them apart.
A Naming Collision
<!DOCTYPE html>
<html>
<body>
<pre>
<root>
<table>
<name>African Coffee Table</name>
<width>80</width>
<length>120</length>
</table>
<table>
<tr>
<td>Apples</td>
<td>Bananas</td>
</tr>
</table>
</root>
</pre>
</body>
</html>Solving It With a Prefix and xmlns
The fix is to qualify each element name with a namespace, declared using the reserved xmlns attribute. The attribute's value is a URI that simply acts as a unique identifier — it doesn't need to point to a real, reachable page. Each element name is then prefixed to say which namespace it belongs to.
Disambiguating With Namespaces
<!DOCTYPE html>
<html>
<body>
<pre>
<root>
<f:table xmlns:f="https://example.com/furniture">
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
<h:table xmlns:h="https://example.com/report">
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
</h:table>
</root>
</pre>
</body>
</html>Default Namespaces
Instead of prefixing every single element, you can declare a default namespace on a parent element using xmlns without a prefix. Every unprefixed child element then belongs to that namespace automatically, until a nested element declares a different one.
A Default Namespace
<!DOCTYPE html>
<html>
<body>
<pre>
<table xmlns="https://example.com/furniture">
<name>African Coffee Table</name>
<width>80</width>
<length>120</length>
</table>
</pre>
</body>
</html>- A namespace is declared with the reserved attribute xmlns or xmlns:prefix.
- The namespace value is a URI used purely as a unique name, not a fetchable web address.
- A prefixed element, like f:table, belongs to whichever namespace its prefix was bound to.
- A default namespace, declared with plain xmlns, applies to the element it's set on plus all of its unprefixed descendants.
- Different elements can safely share a local name, like table, as long as they live in different namespaces.
Exercise: XML Namespaces
What problem do XML namespaces primarily solve?