1. Computing

Discuss in my forum

What is a Namespace?

Avoid Conflicts in Your XML Elements - Use XML Namespaces

By

XML namespaces are a way to avoid conflicts between element names when two (or more) different specifications are in use. For example, if you were a furniture store, you might have an XML driven website that had your entire catalog in XML and you want to display it in XHTML on the Web. For your document you might have an XHTML table like this:

<table>
<tr>
<td>Oak</td>
<td>6'x4'</td>
<td>$300</td>
</tr>
</table>

And your catalog might have a table like this:

<table>
<wood>oak</wood>
<length>6'</length>
<width>4'</length>
<price>$300</price>
</table>

If you merged those two XML documents, you would have a conflict because there is a <table> element in each, but it has different contents and semantic meaning. An XML parser coming across this would be confused and get an error.

XML Namespaces Solve Naming Conflicts

In order to combine those two XML documents you need to define the two namespaces and indicate which <table> element belongs to which namespace.

Setting the Default Namespace

The first thing you need to do when working with namespaces is to set the default namespace. You do this by using the xmlns attribute on the root element of your document. In XHTML that would be the <html> tag:

<html xmlns="http://www.w3.org/1999/xhtml">

XML Namespace Prefixes

But that is only useful if you have only one type of XML in your document. If you're going to have more than one, such as the furniture XML shown above, you'll need a way to define the different namespaces. The easiest way is to define prefixes that will tell the browser what namespace to use for each tag. In the root element, you use the xmlns attribute with a prefix separated by a colon for each namespace you want to define. For example:

<root xmlns:html="http://www.w3.org/1999/xhtml"
xmlns:furniture="http://webdesign.about.com/furniture">

Then, to use those namespaces, you simply add the prefix to your tags, again separated by a colon:

<html:table>
<html:tr>
<html:td>Oak</td>
<html:td>6'x4'</td>
<html:td>$300</td>
</tr>
</table>

<furniture:table>
<furniture:wood>oak</wood>
<furniture:length>6'</length>
<furniture:width>4'</length>
<furniture:price>$300</price>
</table>

Learn more about Declaring XML Namespaces

Did you find this useful?

You can get more articles and information like this by subscribing to the site newsletter or RSS feed.

  1. About.com
  2. Computing
  3. Web Design / HTML
  4. XML
  5. Specifications
  6. XML Namespaces
  7. What is a Namespace - HTML Namespaces - XML Namespaces

©2014 About.com. All rights reserved.