Interview Questions

Does the scope of an XML namespace declaration include the element it is declared on?

XML Interview Questions and Answers


(Continued from previous question...)

79. Does the scope of an XML namespace declaration include the element it is declared on?

Yes.
For example, in the following, the names B and C are in the http://www.bar.org/ namespace, not the http://www.google.org/ namespace. This is because the declaration that associates the google prefix with the http://www.bar.org/ namespace occurs on the B element, overriding the declaration on the A element that associates it with the http://www.google.org/ namespace.
<google:A xmlns:google="http://www.google.org/">
<google:B xmlns:google="http://www.bar.org/">
<google:C>abcd</google:C>
</google:B>
</google:A>

Similarly, in the following, the names B and C are in the http://www.bar.org/ namespace, not the http://www.google.org/ namespace because the declaration declaring http://www.bar.org/ as the default XML namespace occurs on the B element, overriding the declaration on the A element.

<A xmlns="http://www.google.org/">
<B xmlns="http://www.bar.org/">
<C>abcd</C>
</B>
</A>

A final example is that, in the following, the attribute name D is in the http://www.bar.org/ namespace.
<google:A xmlns:google="http://www.google.org/">
<google:B google:D="In http://www.bar.org/ namespace"
xmlns:google="http://www.bar.org/">
<C>abcd</C>
</google:B>
</google:A>

One consequence of XML namespace declarations applying to the elements they occur on is that they actually apply before they appear. Because of this, software that processes qualified names should be particularly careful to scan the attributes of an element for XML namespace declarations before deciding what XML namespace (if any) an element type or attribute name belongs to.

(Continued on next question...)

Other Interview Questions