Lesson 6 | Namespaces |
Objective | Use namespaces to establish clear naming conventions. |
Namespaces establish naming Conventions
The flexibility that XML provides for defining elements may have a downside. There are cases in which you may want to use elements in an XML document from two different DTDs. It is not inconceivable that two elements from two different DTDs have the same name yet an entirely different meaning. For example, one DTD may use the element named <TITLE>
to refer to the title of a book, while another may use the <TITLE>
element to refer to the title of a house. To avoid these naming conflicts, often referred to as name collisions, we have to associate a context with each element name. XML namespaces do just that. Namespaces are defined in W3C recommendation that was added to the XML specification.
Declaring Namespaces
Namespaces are declared using an
xmlns
(xml namespace) declaration with an XML element. An
xmlns
declaration associates the namespace with a unique identifier in the form of a
URI (Uniform Resource Identifier).
In addition, the
xmlns
declaration may specify a prefix that is used to qualify elements and attributes as belonging to that specific
namespace. The SlideShow shows the process for declaring namespaces.
Declaring Namespaces
Namespace scope
The XML namespace scope defines the part(s) of the XML document for which the namespace is in effect or is applicable. The namespace scope is indicated by the location of the xmlns
declaration in the XML document. A namespace definition applies to the element in which it is defined and all descendant (child) elements. As a result, a namespace declaration that is placed with the root element of an XML document is applicable to the entire document.
The descendant, or child, elements inherit the namespace from the parent elements. Even so, a given element can override the inherited namespace by defining its own. Multiple namespaces can also be used in the same document.
For example, the following XML document uses two namespaces identified by the ucedu
and ncedu
prefixes respectively, declared in the root element of the document. In this example, the two <NAME>
elements are clearly distinguished.
<ucedu:COURSE xmlns:ucedu="http://www.ucedu.org/names"
xmlns:ncedu="http://www.ncedu.org/names">
<ucedu:NAME> Introduction to XML programming</ucedu:NAME>
<ncedu:NAME> XML programming </ncedu:NAME>
<ucedu:LOCATION>Sander Hall</ucedu:LOCATION>
<ucedu:TIME> 11:00 am </ucedu:TIME>
</ucedu:COURSE>
Note:
The use of namespace declarations becomes even
more valuable when you are using two or more sets of tags and attributes defined by two or more entities. To declare multiple namespaces, just
add multiple namespace declarations. The next lesson explains the purpose of XML schemas.