Microsoft XML SDK 2.6 - XML Developer's Guide

Reasons for Namespaces

The appeal of XML lies in the ability to invent tags that convey meaningful information. For example, XML allows you to represent information about a book like so:

<BOOK>
  <TITLE>A Suitable Boy</TITLE>
  <PRICE currency="US Dollar">22.95</PRICE>
</BOOK>

Similarly, you can represent information about an author as:

<AUTHOR>
  <TITLE>Mr</TITLE>
  <NAME>Vikram Seth</NAME>
</AUTHOR>

While the human reader can distinguish between the different interpretations of the TITLE element, a computer program does not have the context to tell them apart. Without additional information it cannot tell that the first TITLE element is intended to refer to a string representing the title of the book, and that the second element refers to an enumeration representing the title of the author: "Mr.," "Ms.," "Mrs.," and so on.

Namespaces solve this problem by associating a vocabulary (or namespace) with a tag name. For example, the titles can be written as follows:

<BookInfo:TITLE>A Suitable Boy</BookInfo:TITLE>
<AuthorInfo:TITLE>Mr.</AuthorInfo:TITLE>

The name preceding the colon, the prefix, refers to a namespace, or a Universal Resource Identifier (URI). The URI ensures global uniqueness when merging XML sources, while the associated prefix—a short name that substitutes for the namespace—must be unique only in the tightly scoped context of the document. With this scheme, no conflicts exist between tags and attributes, and two tags can be the same only if they are from the same namespace and have the same tag name. This allows a document to contain both book and author information without confusion about whether the TITLE element refers to the book or the author. If a computer program wanted to display the name of a book in a user interface, it would use the object model to look for the TITLE element of the "BookInfo" namespace.

For more information about namespaces, see the "Namespaces in XML" recommendation on the W3C Web site.