Sunday, January 13, 2008

A Tutorial on XML Namespaces


XML namespaces are used to avoid element name conflicts. A namespace is a set of names in which all names are unique. An XML namespace can be tought as a Java package name. To distinguish two classes of the same name we put the classes in two different packages. For example; you may choose to put a class that is used to connect to a relational database system in com.foo.sql package (com.foo.sql.Connection) and a class that manages TCP/IP socket connections in com.foo.net package (com.foo.net.Connection).

An XML namespace is used in the same way. Namespaces make it easier to come up with unique names. Without namespaces all XML element names must be unique all over the world. I'll try to explain this with an example.

Xml representation of a java class.

<class>
<name>com.foo.bar.Customer</name>
<method>getName</method>
<method>setName</method>
<superclass>com.foo.bar.Person</superclass>
</class>

Xml representation of a college class.

<class>
<code>MATH101E</code>
<name>Mathematics 1</name>
<language>English</language>
<credits>4</credits>
<class>

If these two "class" XML elements are used in the same XML document there will a name conflict. These name conflicts can be resolved by using namespaces.

<j:class xmlns:j="http://java.sun.com/class">
<j:name>com.foo.bar.Customer</j:name>
<j:method>getName</j:method>
<j:method>setName</j:method>
<j:superclass>com.foo.bar.Person</j:superclass>
</j:class>

<itu:class xmlns:itu="http://java.sun.com/class">
<itu:code>MATH101E</itu:code>
<itu:name>Mathematics 1</itu:name>
<itu:language>English</itu:language>
<itu:credits>4</itu:credits>
</itu:class>

ITU : Istanbul Technical University

XML namespaces are defined with XML Namespace (xmlns) Attribute. The XML namespace attribute is placed in the start tag of an element and has the following syntax:

xmlns:namespace-prefix="namespaceURI"

When a namespace is defined in the start tag of an element, all child elements with the same prefix are associated with the same namespace.
If this tutorial is not enough for you can read these articles:
  • Xml namespaces from w3schools
  • Understanding XML Namespaces from Micro$oft MSDN library
  • XML Namespaces by Example from xml.com
  • Xml namespaces from wikipedia
  • XML Schema: Understanding Namespaces from Oracle

  • 1 comments:

    Anonymous said...

    Hello. This post is likeable, and your blog is very interesting, congratulations :-). I will add in my blogroll =). If possible gives a last there on my site, it is about the CresceNet, I hope you enjoy. The address is http://www.provedorcrescenet.com . A hug.