On this blog, I’ve been writing about the semantic web and its technologies. This began with a primer on URIs, and continued with an introduction to RDF. The next step in that journey will be to explore RDF/XML: the XML representation of RDF. But first, it is important to take stock of a very important feature in XML, XML namespaces. XML namespaces are quite useful outside of the context of the semantic web too, since really all they are is a way to avoid naming conflicts, but RDF/XML wouldn’t really be possible without namespaces, so we should take a moment to appreciate these often overlooked data structures.
An XML namespace maps some URI to a local name you use in your XML document when defining elements. In RDF/XML, they might refer to a particular URL where a vocabulary has been published, but that isn’t a requirement. It really just needs to be some valid URI- whether it is a URL or URN doesn’t matter, since the parser doesn’t look up that link. To define this mapping, simply put the “xmlns” attribute on any XML node using the namespace you are defining. Namespaces are often declared in the document’s root element so they can apply to the whole document. This common practice leads to the misconception that xmlns attributes must be in the root, but that isn’t the case, they can be placed in any node in your XML document.
The basic syntax for this attribute is:
xmlns:localName = “http://www.myuri.com/path”
Once that is done, whenever you define an element in your XML doc, you use the local name prefix on it, like so:
Since that can get verbose, you will find in practice that the local name is often only one or two characters long.
It is possible to specify a namespace in an XML document and not add the localName portion when you define it, like so:
xmlns = “http://www.myuri.com/path”
This is now the default namespace for everything under it. Other namespaces can still be used, but when a localName isn’t specified that is the assumed namespace for all elements that don’t explicitly declare the local name.
That’s all there is to it. Now your XML document can have element names that don’t collide. When combined with the semantic web notion of vocabularies, and using XML to express RDF, namespaces provide an especially elegant solution. You can create an RDF/XML document that draws from many different vocabularies and not worry about confusion because each vocabulary has its own namespace.
I’ll finish up this post with a simple XML namespace example published by the W3 Schools.
<f:name>African Coffee Table</f:name>