1. Technology

XML Namespaces - A Closer Look

Defining Namespaces in XML

By

For some, the theory behind XML namespaces may be complicated, but a closer look shows them to be an easy tool. When developing a document in XML, the author makes up tags names. This is an exciting development in computer languages, but a whopping problem as well. If two pages use the same tag for different purposes, how does the parser distinguish between them? Let's look at a case where one tag might have two meanings.

<?xml version="1.0" ?>
<colortheory>
    <orange>
        <approach> Mix red and yellow pigments together </approach>
    </orange>
</colortheory>

<?xml version="1.0" ?>
<fruitcatalog>
    <orange>
        <description> round citrus fruit </description>
    </orange>
</fruitcatalog>

A human eye can look over this code and easily see that <orange> in the first example refers to a color and in the second, a fruit. A parser does not have that luxury. Namespace is a tool to individualize element tags.

Uniform Resource Identifier (URI)

The Uniform Resource Identifier (URI) is an abstract web address that distinguishes namespaces. When a parser sees a URI associated with an XML tag, it incorporates that address into the definition of the tag to identify it. A parser will merge the element name and the URI to create a distinctive tag. This does not mean that the browser will open a URI address; it is not a link, but a defining tool. The address listed in the code does not need to provide any information to the parser, such as schema addresses or DTD. The URI gives a way to connect the tag to something unique. If you are standing in a room full of people and call out the name 'Mary,' three different women may respond. If you call out the name 'Mary Connell,' you have individualized 'Mary' and made the name unique. A URI works in the same way to distinguish like tag names.

By incorporating the code 'xmlns' into the element name, you can establish a namespace for 'orange'.

<?xml version="1.0" ?>
<colortheory>
   <orange xmlns="http://www.mycolorpages.com/colortheory">
        <approach> Mix red and yellow pigments together </approach>
   </orange>
</colortheory>

This example extends the tag name <orange> to include a URI. For a parser, this URI is now part of the tag and segregates it from <orange> fruit.

  1. About.com
  2. Technology
  3. Web Design / HTML
  4. XML
  5. Specifications
  6. XML Namespaces
  7. XML Namespaces - Learning More About XML Namespaces

©2014 About.com. All rights reserved.