Considering the following XML document:
2 x:foo="123" xmlns:x="foo">
3 <b xmlns="bar"
5 <c xmlns:x="baz">
6 <x:d xmlns="">
7 <e xmlns:y="asdf"/>
10 <f xmlns:x="bar"/>
For lines 1–7 and 10, which namespace URI does the element or attribute declared on that line have? Some kind of explanation would be much appreciated.
Best How To :
Here's a quick summary.
When you use
xmlns without declaring a prefix, the namespace it declares be inherited by all elements in that scope (the element where you declared it and all the unprefixed elements it contains, until another
xmlns with a different value is declared).
Attributes don't inherit namespaces. They must be qualified with a prefix.
When you use
xmlns:prefix, the namespace it declares be inherited by all prefixed elements in that scope (the prefixed element where you declared it and all the prefixed elements it contains, until another
xmlns:prefix with a different value is declared). If the element where it is declared does not have the same prefix, or no prefix, it will not be part of the namespace.
Based on that, in your example:
e belong to no namespace.
a because it has no
xmlns declaration and no parents.
e because its parent has a
xmlns='' attribute which makes the default namespace null.
f belong to the
b because it declares the default namespace as
xmlns='bar' and has no prefix.
f because they have no prefix and inherit the default namespace from their parent.
d belongs to the
baz namespace because of the
x prefix which explicitly qualifies it, but its unqualified contents (
e) now belong to no namespace because of
e declares the
asdf namespace and assigns it to the
y prefix but no element or attribute uses it.
f redeclares the
x atrribute with a different namespace
bar which would be applied to any prefixed child of
f if there were any (or to
f if it were prefixed by
foo attribute in
a belongs to the
foo namespace, because it is qualified by the
y attribute in
b belongs to no namespace, because it has no prefix.
See the other answer by @MichaelKay which links to a very good tutorial on the subject.