XML Namespaces
XML Namespaces provide a method to avoid element
name conflicts.
Name Conflicts
In XML, element names are defined by the developer. This often
results in a conflict when trying to mix XML documents from different
XML applications.
For example, consider the following XML document that carries
information about HTML table example:
<table>
<tr>
<td>Apples</td>
<td>Bananas</td>
</tr>
</table>
XML
• The following is an XML document that carries
information about a table (a piece of
furniture):
• <table>
<name>African Coffee Table</name>
<width>80</width>
<length>120</length>
</table>
XML Documents Must Have a Root Element
• XML documents must contain one root element that is
the parent of all other elements:
<root>
<child>
<subchild>.....</subchild>
</child>
</root>
If these XML fragments were added together, there
would be a name conflict. Both contain a <table>
element, but the elements have different content and
meaning.
Two Ways to solve
1.Solving the Name Conflict Using a Prefix
2.XML Namespaces - The xmlns Attribute
1.Solving the Name Conflict Using a Prefix
Name conflicts in XML can easily be avoided using a name
prefix.
This XML carries information about an HTML table, and a
piece of furniture:
<h:table>
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
</h:table>
<f:table>
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
•In the example above, there will be
no conflict because the two <table>
elements have different names.
•Drawback:
If prefix itself same for more than
one xml document, then again name
conflict occurs. To avoid this we can
use xml namespace along with prefix
2.XML Namespaces - The xmlns Attribute
When using prefixes in XML, a namespace for the
prefix must be defined.
The namespace can be defined by
an xmlns attribute in the start tag of an element.
The namespace declaration has the following
syntax. xmlns:prefix="URI".
The namespace declaration has the following syntax:
• <element-name
xmlns:prefix="URI">
Where
The Namespace starts with the keyword xmlns.
The word prefix is the Namespace prefix.
The URI is the Namespace identifier.
Sample Code:
<root>
<h:table xmlns:h="http://www.w3.org/TR/html4/">
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
</h:table>
<f:table xmlns:f="https://www.w3schools.com/furniture">
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
</root>
•In the example above:
The xmlns attribute in the first
<table> element gives the h: prefix
a qualified namespace.
The xmlns attribute in the second
<table> element gives the f: prefix a
qualified namespace.
When a namespace is defined for an
element, all child elements with the
same prefix are associated with the
same namespace.