Codrin Faca
Codrin Faca

Reputation: 85

XML - Namespaces

Considering the following XML document:

1 <a
2     x:foo="123" xmlns:x="foo">
3  <b xmlns="bar"
4      y="456">
5   <c xmlns:x="baz">
6    <x:d xmlns="">
7     <e xmlns:y="asdf"/>
8    </x:d>
9   </c>
10  <f xmlns:x="bar"/>
11 </b>
12 </a>

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.

Upvotes: 1

Views: 93

Answers (2)

helderdarocha
helderdarocha

Reputation: 23627

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:

  • a and 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.

  • b, c and f belong to the bar namespace. b because it declares the default namespace as xmlns='bar' and has no prefix. c and 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 xmlns=''.

  • 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 x).

  • The foo attribute in a belongs to the foo namespace, because it is qualified by the x prefix.

  • 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.

Upvotes: 1

Michael Kay
Michael Kay

Reputation: 163587

James Clark's explanation of namespaces

http://www.jclark.com/xml/xmlns.htm

remains as good as any. If you still have questions after reading that, then tell us which parts you don't understand.

Upvotes: 2

Related Questions