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:
And your catalog might have a table like this:
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:
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:
Then, to use those namespaces, you simply add the prefix to your tags, again separated by a colon:
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.