XML namespaces and attributes

user4315 picture user4315 · Sep 3, 2008 · Viewed 29.1k times · Source

I'm trying to understand how namespaces work in XML. When I have an element like foo:bar, the attributes will often not have namespaces on them. But sometimes they will. Are the attribute in the namespace of the element, even when the default namespace has been declared? Looking over the xsd for xhtml it seems the attributes are part of the schema and should be in the namespace for xhtml, but they are never presented that way...

Answer

Bart Schuller picture Bart Schuller · Sep 5, 2008

Most of the time, attributes will not be in any namespace. The namespace spec says (emphasis mine):

A default namespace declaration applies to all unprefixed element names within its scope. Default namespace declarations do not apply directly to attribute names; the interpretation of unprefixed attributes is determined by the element on which they appear.

There's a reason that most XML vocabularies use non-namespaced attributes:
When your elements have a namespace and those elements have attributes, then there can be no confusion: the attributes belong to your element, which belongs to your namespace. Adding a namespace prefix to the attributes would just make everything more verbose.

So why do namespaced attributes exist?
Because some vocabularies do useful work with mostly attributes, and can do this when mixed in with other vocabularies. The best known example is XLink.

Lastly, W3C XML Schema has an all too easy way (<schema attributeFormDefault="qualified">) of declaring your attributes as being in a namespace, forcing you to prefix them in your documents, even when you use a default namespace.