XML Namespaces
XML namespaces are used to avoid name conflicts between XML elements.
Name Conflicts between XML Elements and Resolution
A conflict could happen when you try to mix XML documents from different XML application.
The following is an example of conflict:
<table>
<tr>
<td>Milan</td>
<td>Rome</td>
<td>Venice</td>
</tr>
</table>
<table>
<name>PC desk</name>
<width>90</width>
<length>150</length>
</table>
Both contain a <table>
element but the XML elements have different content and meaning. If they merged together, there would be a name conflict.
To resolve name conflicts we use a name prefix.
For example:
<firstprefix:table>
<firstprefix:tr>
<firstprefix:td>Milan</firstprefix:td>
<firstprefix:td>Rome</firstprefix:td>
<firstprefix:td>Venice</firstprefix:td>
</firstprefix:tr>
</firstprefix:table>
<secondprefix:table>
<secondprefix:name>PC desk</secondprefix:name>
<secondprefix:width>90</secondprefix:width>
<secondprefix:length>150</secondprefix:length>
</secondprefix:table>
In this way, we have resolved the conflict: elements of the first table have firstprefix:
prefix while elements of the second table have secondprefix:
prefix.
Basically, we changed the <tagname>
to <prefixname:tagname>
with prefixes to resolve conflicts
XML Namespace
A namespace must be defined in order to use prefixes in XML.
The namespace is defined using an xmlns
attribute in the start tag of an element, following this syntax: xmls:prefixname="URI"
.
<root>
<firstprefix:table xmlns:firstprefix:tr="http://www.w3.org/TR/html4/">
<firstprefix:tr>
<firstprefix:td>Milan</firstprefix:td>
<firstprefix:td>Rome</firstprefix:td>
<firstprefix:td>Venice</firstprefix:td>
</firstprefix:tr>
</firstprefix:table>
<secondprefix:table xmlns:secondprefix:name="https://tutorialreference.com/furniture">
<secondprefix:name>PC desk</secondprefix:name>
<secondprefix:width>90</secondprefix:width>
<secondprefix:length>150</secondprefix:length>
</secondprefix:table>
</root>
Namespaces can also be declared in the XML root element
<root xmlns:firstprefix="first-URI" xmlns:secondprefix="second-URI">
...
</root>
The purpose of the URI is to give the namespace a unique name. Also, it isn't used by the parser.
XML Namespace as Default Namespace
Defining a default namespace avoids the use of prefixes in all descendant elements.
A default namespace is written as xmlns="namespaceURI"
.
For example:
<table xmlns="http://www.w3.org/TR/html4/">
<tr>
<td>Milan</td>
<td>Rome</td>
<td>Venice</td>
</tr>
</table>
<table xmlns="https://tutorialreference.com/furniture">
<name>PC desk</name>
<width>90</width>
<length>150</length>
</table>
Namespaces and XSLT
XSLT is a language used to transform XML documents into other formats.
Read our XSLT Tutorial to learn more about XSLT.