Name conflict is a common day occurrence. When you’re blessed with a popular name like Mohamed, Jack, or Michael, name conflict is even more familiar. Luckily, in the real world, we have inherit attributes, such as physical appearance, that can easily allow someone to distinguish between one Michael and the next. However, bare XML documents do not have that luxury. Certainly, the contents of these conflicting nodes may be enough to tell the difference, but there is a more elegant and reliable solution.
Namespaces are lists of pre-defined names and attributes for XML elements. Some very common namespaces include XHTML and XSLT. However, when dealing with complex data covering a variety of topics, name conflict becomes increasingly more common. Let’s say we’re indexing a warehouse:
<warehouse> <crate size="medium"> <animal>Dog</animal> </crate> ... <crate size="large"> <painting> <artist>Some Dead Guy</artist> <title>Untitled #387</title> </painting> </crate> </warehouse>
Here, we have two different crates carrying two vastly different things. The type of crate we might use to transport an animal is vastly different from the type of craft that we would transfer artwork in. Also notice the attributes used on these two different crate elements. At first glance, we likely assume these are directly related the size of the crate. However, couldn’t the size attribute of the crate define what type of crate to use? We wouldn’t use a large dog kennel for transporting mice, as they would be able to simply run out the holes. We would rather use a crate more suited for carrying small animals, and thus this size attribute may carry more meaning than just physical size.
This is where namespaces come into play. In our example above, we would direct our XML document to use specific namespaces for animal and art transportation. An example namespace can be found here: http://www.w3.org/1999/xhtml. Namespace documents don’t have specific rules to follow, but rather are responsible for explaining what the namespace elements and attributes are. Then, these namespaces can be used for reference by others using our XML files to determine what particular elements and attributes mean.
Including namespaces are simple, and can be done inline with a particular element or at the root element using the
xmlns attribute, i.e.
<warehouse xmlns:m="http://acmecrates.com/museum" xmlns:z="http://acmecrates.com/zoo"> <z:crate size="medium"> <animal>Dog</animal> </z:crate> ... <m:crate size="large"> <painting> <artist>Some Dead Guy</artist> <title>Untitled #387</title> </painting> </m:crate> </warehouse>