XML Namespace

In XML, a namespace is used to prevent any conflicts with element names.

Because XML allows you to create your own element names, there's always the possibility of naming an element exactly the same as one in another XML document. This might be OK if you never use both documents together. But what if you need to combine the content of both documents? You would have a name conflict. You would have two different elements, with different purposes, both with the same name.

Example Name Conflict

Imagine we have an XML document containing a list of books. Something like this:

And imagine we want to combine it with the following HTML page:

We will encounter a problem if we try to combine the above documents. This is because they both have an element called title. One is the title of the book, the other is the title of the HTML page. We have a name conflict.

What we can do to prevent this name conflict is, create a namespace for the XML document.

Example Namespace

Using the above example, we could change the XML document to look something like this:

We have added the xmlns:{prefix} attribute to the root element. We have assigned this attribute a unique value. This unique value is usually in the form of a Uniform Resource Identifier (URI). This defines the namespace.

And, now that the namespace has been defined, we have added a bk prefix to our element names.

Now, when we combine the two documents, the XML processor will see two different element names: bk:title (from the XML document) and title (from the HTML document).

Note: If you have defined your tags and attributes in a DTD, you will need to update your DTD in order to make the new element names legal.