Interview Questions

Why are special attributes used to declare XML namespaces?

XML Interview Questions and Answers


(Continued from previous question...)

72. Why are special attributes used to declare XML namespaces?

I don't know the answer to this question, but the likely reason is that the hope that they would simplify the process of moving fragments from one document to another document. An early draft of the XML namespaces recommendation proposed using processing instructions to declare XML namespaces. While these were simple to read and process, they weren't easy to move to other documents. Attributes, on the other hand, are intimately attached to the elements being moved.
Unfortunately, this hasn't worked as well as was hoped. For example, consider the following XML document:

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

Simply using a text editor to cut the fragment headed by the <B> element from one document and paste it into another document results in the loss of namespace information because the namespace declaration is not part of the fragment -- it is on the parent element (<A>) -- and isn't moved.
Even when this is done programmatically, the situation isn't necessarily any better. For example, suppose an application uses DOM level 2 to "cut" the fragment from the above document and "paste" it into a different document. Although the namespace information is transferred (it is carried by each node), the namespace declaration (xmlns attribute) is not, again because it is not part of the fragment. Thus, the application must manually add the declaration before serializing the document or the new document will be invalid.

(Continued on next question...)

Other Interview Questions