Wednesday, March 17, 2010

Namespace in XML

Kevluan, Mar 8, 2010

Namespace is a concept broadly used in prime programming language libraries to resolve naming conflicts. XML uses namespace for the same purpose. However, the interpretation of namespace in XML is not as straightforward as in libraries. First of all, namespace is declared on an element; Secondly, attributes of an element also have namespace; Thirdly, a specific parser may be used to understand certain namespace.

Let's start with an example:

<x xmlns:edi='http://ecommerce.example.org/schema'>
<!-- the "edi" prefix is bound to http://ecommerce.example.org/schema
for the "x" element and contents -->
</x>

The comments in the code snippet - "the namespace specified by "edi" is applied to "x" and contents". Here contents mean the sub-elements. Because namespace is an attribute of an XML element or an attribute of an XML element, the declared namespace can be applied to both elements and attributes inside of the element where the namespace declared.

When an XML element doesn't have an explicit namespace prefix, default namespace is applied, which is the namespace inherited from parent element or ancesters.

But, default namespace does not apply to attributes. Look at the following example:

<!-- http://www.w3.org is bound to n1 and is the default -->
<x xmlns:n1="http://www.w3.org"
xmlns="http://www.w3.org" >
<good a="1" b="2" />
<good a="1" n1:a="2" />
</x>

It is important to realize the difference between "n1:a" and "a". Even attribute "a" is inside of element "x" that has default namespace of the same value of "n1". "a" and "n1:a" are different attributes. That says a local attribute without explicitely applied namespace is empty namespaced, rather than inherit the namespace from enclosed element.

The tricky thing is, attributes inherit namespace from the element they live:

<xsl:for-each select="catalog/cd">

Here, "select" attribute has the namespace of "xsl" that is beared to its living element "for-each".

To recap, an local element (without explicit namespace) inherits namespace if it has an ambient element that defined namespace, while an attribute only get default namespace from the element it attaches.


Namespace and Parser

In following code snippet,

<xsd:schema xmlns:xsd="http://www.w3.org/1999/XMLSchema" ...>
<xsd:element xsd:name="BookCatalogue">
...
</xsd:element>
...
</xsd:schema>

we see elements and attributes in XML Schema namespace, it means that XML Schema parser would understand them.

How xpath works with namespace ...

Reference:
[1] http://www.w3.org/TR/REC-xml-names/

No comments: