So I've been reading about namespace on w3schools and I understand they are to uniquely identify an element. But what is the point of having namespaces if you have to have prefixes along side them. Are you always required to have prefixes with namespaces? If not are you always required to have namespaces with prefixes? If so why?
For example:
<root xmlns:h="http://www.w3.org/TR/html4/" xmlns:f="http://www.w3schools.com/furniture">
<h:table>
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
</root>
Doesn't f and h uniquely identify the different element types?
Thanks for your help. I'm really at a loss at understanding why namespaces exists.
Best Answer
An XML namespace is supposed to have a reasonable chance of being universally unique. A prefix, especially a single-letter one, is almost certain not to be. A namespace declaration creates a mapping from an otherwise meaningless prefix to a stable identifier that software can rely on to identify the schemas of XML elements.
You're right: within a single document, an author can make sure that different prefixes are used for different groups of elements. But without tying those prefixes to unique namespaces, how do you accomplish any of the following:
h
with the collection of HTML elements, and therefore knows how to renderh:table
?There is no central database of prefixes where
h
is forever and all time associated with HTML elements - that's the purpose of the namespace declaration mapping the prefix to the namespace within the scope of the document.Update - clarification of terminology
xmlns
. If you really wanted to, you could have bothxmlns:f="http://www.w3schools.com/furniture"
andxmlns:argos="http://www.w3schools.com/furniture"
, and then use the prefixes interchangeably:<f:table>
or<argos:table>
. The parser doesn't care whether the prefix isf
orargos
- it only cares that both of thesetable
elements belong to the namespacehttp://www.w3schools.com/furniture
. Further, the URLhttp://www.w3schools.com/furniture
does not have to be a valid document. When used as an XML namespace URI, its only function is to be a unique identifier. If the parser had available a schema whosetargetNamespace
washttp://www.w3schools.com/furniture
, it could validate thetable
elements and their contents using that schema.