XML namespaces and attributes
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...
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.
Examples to illustrate using the Clark notation, where the namespace prefix is replaced with the namespace URL in curly brackets:
<bar xmlns:foo="http://www.foo.com/"
foo:baz="baz"
qux="qux"/>
<bar xmlns="http://www.foo.com/" xmlns:foo="http://www.foo.com/"
foo:baz="baz"
qux="qux"/>
<foo:bar xmlns="http://www.foo.com/" xmlns:foo="http://www.foo.com/"
foo:baz="baz"
qux="qux"/>
is
<{}bar
{http://www.foo.com/}baz="baz"
{}qux="qux"/>
<{http://www.foo.com/}bar
{http://www.foo.com/}baz="baz"
{}qux="qux"/>
<{http://www.foo.com/}bar
{http://www.foo.com/}baz="baz"
{}qux="qux"/>