XML namespaces tutorial

XML namespaces are a way to disambiguate names in XML documents, thus helping avoid a collision of names when multiple XML vocabularies are used together. Here's a simple namespace declaration:

<document xmlns="http://www.ns.com/ns/document">

This is a default namespace declaration. We can also have qualified or prefixed namespace declarations, like this:

<doc:document xmlns:doc="http://www.ns.com/ns/document">

As you can see, the xmlns attribute (with or without a prefix) specifies a namespace declaration. Namespaces can be quite confusing because they use any URI as a namespace name. The HTTP protocol scheme used above may suggest that we're actually using a resource that can be retrieved by fetching the given URI, but this is not the case. The URI is simply a name and it doesn't guarantee the location or existence of a resource. URIs are used locally. The main downside of this is that you can't really make sure if other people are using your domain name as a part of their URI.

A default namespace declaration is a namespace declaration without any prefix attached to the xmlns attribute. A default namespace declaration associates a namespace name (a URI) with one or more elements, but not with attributes. Attributes without a prefix are not considered part of any namespace.

A local name combined with its namespace name is called an expanded name and is oftend represented in descriptive text as {http://www.ns.com/ns/document}document, though it is never represented this way in XML. The dafault declarations associates the namespace name with an element and its children or descendant elements. A default declaration on the document element applies to elements in the entire document, but not to attributes.

So if you use getElementsByTagNameNS(namespace, elements) either on an XML or XHTML document, you can actually match all elements that live in a given namespace (in XHTML is http://www.w3.org/1999/xhtml), but you cannot match attributes, because they don't belong to the namespace itself.

Instead, in a prefixed namespace declaration, the prefix (such as doc) is associated with the namespace name, thus making the name a qualified name. If you want to associate a namespace to an attribute, you have to use a prefix in its name. Again, an attribute that doesn't have a prefix is never associated with any namespace. You can do this only by using a prefix. Default namespace declarations never apply to attributes.

Links for further reading

Leave a Reply

Note: Only a member of this blog may post a comment.