Note: The Console blog is no longer active. I'm currently building the Sculpted Code blog, and when it's finished, I shall be posting there.
← Console Index
Introduction to Namespaces in XML

Namespaces were introduced in order to avoid conflicts with names of XML elements and attributes. For example, say you have a “table” element (thanks to W3Schools for this example). It could apply to either a piece of furniture or an HTML element used for displaying data. If, for some reason, these two pieces of code needed to be combined, there would be a conflict. To avoid these conflicts and to give these elements unique identifiers, we use namespaces.

Throughout this post, I shall use custom (namespaced) RSS elements/attributes from the Sparkle framework as examples.

About Namespaces

A namespaced element looks like this:

<sparkle:releaseNotesURL></sparkle:releaseNotesURL>

// "sparkle" is the namespace and "releaseNotesURL" is the element name

A namespaced attribute looks like this:

<enclosure sparkle:version="1.0" url="foo.zip" />

// "sparkle" is the namespace and "version" is the attribute name

A URL must also be associated with the namespace. This is usually specified on the root element using the xmlns attribute:

<rss version="2.0" xmlns:sparkle="http://www.andymatuschak.org/xml-namespaces/sparkle">
 <!-- Declaring the "sparkle" namespace on the "rss" element -->
</rss>

The xmlns URL doesn’t have to be a real URL, as it’s just an identifier for the namespace, but people often use it to reference a page describing/documenting the namespace.

Parsing Namespaces

When parsing XML, you may have to parse a namespaced element or attribute.

At first, you might try to extract the releaseNotesURL element like this (where response is the response XML from an XMLHttpRequest):

response.getElementsByTagName("sparkle:releaseNotesURL")[0];

However, this doesn’t work. You have to use getElementsByTagNameNS:

response.getElementsByTagNameNS("http://www.andymatuschak.org/xml-namespaces/sparkle", "releaseNotesURL")[0];

Note here that getElementsByTagNameNS takes two parameters: the namespace URL and the actual element name.

The same applies to attributes. To extract the version attribute from an enclosure element (assuming that the variable enclosure has already been declared):

enclosure.getAttributeNS("http://www.andymatuschak.org/xml-namespaces/sparkle", "version");

An interesting thing to note is that the latest version of Safari supports

enclosure.getAttribute("sparkle:version");

…but it doesn’t support

enclosure.getElementsByTagName("sparkle:releaseNotesURL");

So, for now, it’s safest to always use the namespace methods…

That’s it for now!