Friday, April 2, 2010

XML Namespaces

XML Namespaces are identified by a URI reference. Both elements and attributes can be defined within namespaces. Namespaces are brought into a document using the reserved attributes xmlns, which defines the default namespace, or xmlns:<str> which binds <str> to the actual URI reference defining the namespace. <str> is referred to as the namespace name. Elements and attributes are prefixed with <str>: to indicate that they belong to the namespace that <str> has been bound to. The element or attribute name is referred to as a local name. The combination of <str>:<name> is referred to as a qualified name. Note that if <name> is in the default namespace then this is also the qualified name.

An example of using a default namespace:

<?xml version="1.0" ?>

<book xmlns="">
  <title type="main">Hello World</title>
  <author>J.Q. Citizen</author>

The same example with a bound, named namespace:

<?xml version="1.0" ?>

<book:book xmlns:book="">
  <book:title book:type="main">Hello World</book:title>
  <book:author>J.Q. Citizen</book:author>

Multiple namespaces can be introduced:

<?xml version="1.0" ?>

<product:book xmlns:product=""
  <bookattr:title bookattr:type="main">Hello World</bookattr:title>
  <bookattr:author>J.Q. Citizen</bookattr:author>

Namespaces have scope from the start element in which they are declared through to the corresponding end element.

Note that even though namespaces can look like URLs they are just treated as strings by an XML processor. A namespace aware XML processor will not reach out to the URL to get something when it encounters a namespace declaration.

No comments: