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.
This
XML carries HTML table information:
<table>
<tr>
<td>Apples</td>
<td>Bananas</td>
</tr>
</table>
This
XML carries information about a table (a piece of furniture):
<table>
<name>Coffee
Table</name>
</table>
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.
An
XML parser will not know how to handle these differences.
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>Coffee
Table</f:name>
</f:table>
In
the example above, there will be no conflict because the two <table>
elements have different names.
The
xmlns Attribute
The
namespace is defined by the xmlns attribute in the start tag of an
element.
namespace
declaration syntax
→ xmlns:prefix="URI"
ex
-
<f:table
xmlns:f=”http://www.sanjeeva.com/furniture”>
*
When a namespace is defined for an element, all child elements with
the same prefix are associated with the same namespace.
*
Namespaces can be declared in the elements where they are used
or in the XML root element.
ex
-
<root
xmlns:h="http://www.w3.org/TR/html4/"
xmlns:f="http://www.sanjeeva.com/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:table>
</root>
Default
Namespaces
: Defining
a default namespace for an element saves us from using prefixes in
all the child elements.
<table
xmlns="http://www.w3.org/TR/html4/">
<tr>
<td>Apples</td>
<td>Bananas</td>
</tr>
</table>
<table
xmlns="http://www.sanjeeva.com/furniture">
<name>African
Coffee Table</name>
</table>
Reference
: http://www.w3schools.com