Namespaces

You can use a namespace to scope elements and attributes in a document. Namespaces are useful in restricting the query search to the meaningful elements within the document.

In XML, element and attribute names are chosen by the developer. These names can create conflicts when XML documents from different applications are mixed.

Therefore, restricting the query search to the meaningful elements within the document is useful, especially when multiple document types might be indexed. Restricting the search can be accomplished by using namespaces.

Namespaces provide scoping of the elements and attributes of the document to ensure correct interpretation of the values. Namespaces are described with a long name (URI), and optionally, a short name that is called the qualified name (QName).

Consider the following example:

<?xml version='1.0'?>
  <doc xmlns:x="http://example.com/ns/abc">
    <x:p/>
  </doc>

http://example.com/ns/abc is the long name and x is the QName prefix. A QName prefix is useful as a shorthand for the namespace of each element reference. Element p is qualified by namespace http://example.com/ns/abc.

Default namespaces

A default namespace can be specified for XML elements. The default namespace applies to the current tag and any descendent tags. Any unqualified tag in the namespace inherits the default namespace.

In the following example, both doc and p elements are in the http://example.com/ns/abc namespace.

<?xml version='1.0'?>
  <doc xmlns="http://example.com/ns/abc">
    <p/>
  </doc>

Attribute namespaces

An attribute might have a different namespace than its associated element.

The following code example shows the qualified element and attribute:

<dog xmlns:an="http://example.org/animals" xmlns:sz=”http://example.org/sizes”>
<an:breed sz:size=”Medium”>Mutt</an:breed>
</dog>

There is a difference in how elements and attributes inherit a namespace when it is not explicitly specified. Unqualified elements pick up the default namespace of the scope within which they lie. Unqualified attributes do not have any namespace.

This next example shows the element and attribute as non-qualified:

<dog xmlns:an="http://example.org/animals">
<breed size=”Medium”>Mutt</an:breed>
</dog>

In this example, element breed has a namespace of http://example.org/animals. However, attribute size has no namespace associated with it.

For more information about XML namespaces, see W3C Recommendation for Namespaces in XML.

Reserved QName prefixes

The following QName prefixes are reserved and must not be used to qualify user-defined elements or attributes: xml, xs, xsi, fn, local.