Namespaces

XML, Part 5: Namespaces

Version 1.31

Namespaces

You can use XML without namespaces, but if you're mixing document types—for example, putting a bit of SVG into an XHTML web page—you'll need to use namespaces to keep things straight.

Uniqueness

Namespaces play the same role in XML as modules in Python and packages in Java. They provide for unique names, even though many developers may write many DTDs, modules, and packages.

An element or attribute name can be qualified or unqualified. If it's qualified, it's used with a namespace; if unqualified, it's not. An example of a qualified name is acme:rocket-kit, where acme refers to (imaginary) "Acme" namespace. An example of an unqualified name is rocket-kit.

In order to confer uniqueness on qualified names, a namespace must itself have a unique name. These unique names are URIs. A URI may be a URL or a URN (p. 92); usually, it's a URL. In this case, the unique identifier of the "Acme" namespace might be "http://acme.example.com/ns/acme/".

The idea is, the developer of the document type owns a particular URL and can lay claim to it. If it's a URL, there doesn't necessarily have to be a page at that URL; the URL is just used to confer uniqueness on the name of the namespace. Java developers follow a similar practice to make Java package names unique.

Elements and Namespaces

An element can either have no namespace, or one or more namespaces. The namespaces, if any, apply to the element and its children in the document tree, unless the children declare their own namespaces.

An element that uses namespaces can have a default namespace, and it can have explicit namespaces identified by prefixes.

Examples:

Notice the way the top-level element declares the namespaces and how that element and its children reference the namespaces either by default or by prefix.

An element can have at most one default namespace, but it can have any nummber of explicit namespaces.


  1. Version history:
    • Version 1.3, 2012 Mar 22. New examples of no namespace, default namespace, and explicit namespace.
    • Version 1.2, 2012 Mar 16. Split parts 4 and 5 into separate files.
    • Version 1.1, 2011 Apr 8. Moved distinction between XML application and XML processor from footnote to section. Changed string concatenation example from Java to Python. Reformatted result of substitution in "little boys and girls" and added arrows.
    • Version 1.0, 2011 Apr 6. Added entities, notations, and namespaces.
    • Version 0.1, 2011 Apr 6. Incomplete draft, covering only comments and character data.