Web Technology - Old Questions

9. What is XML namespace? How it is used in XML files?

5 marks | Asked in Model Question

XML Namespace is a mechanism to avoid name conflicts by differentiating elements or attributes within an XML document that may have identical names, but different definitions.

Consider two XML fragment:

//1.xml

<table>

  <tr>

    <td>Apples</td>

    <td>Bananas</td>

  </tr>

</table>

//2.xml

<table>

  <name>African Coffee Table</name>

  <width>80</width>

  <length>120</length>

</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.

XML namespace is used in XML files as:

1) Using a prefix

Name conflicts in XML can easily be avoided using a name prefix.

E.g.

<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 this example, there will be no conflict because the two <table> elements have different names.

2) Using 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".

E.g.
<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>

The purpose of using an URI is to give the namespace a unique name.