Saturday, December 17, 2011

Understanding the XML Namespace

If your a java programmer the probability that you have run into XML configuration is pretty high. Many frameworks require XML based configuration and even when they offer alternatives (usually Annotations) they usually recommend using XML.

Whether you like it or not XML is everywhere.

So what exactly is the XML namespace. Many a times it just some boiler plate that's added to the beginning of a config document.


Use Spring? Here is what you might have,

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-2.0.xsd">

    <bean id="xyz" class="blogspot.javachats.XYZ"></bean>

    <util:properties id="someConfiguration" 
         location="classpath:blogspot/javachats/some.properties"/>
</beans>

So what is the XML namespace?

All the tags that start with xmlns form the XMLNameSpace tags.

In this example we have three namespaces defined - 1 is implicitly used (referred as Namespace Defaulting) and 2 are explicitly named (referred as Qualified Names). Were you able to identify which is which?

  1.  Namespace Defaulting
    The namespace xmlns="http://www.springframework.org/schema/beans" defines a default namespace. It means that a Non-Qualified tag against which it is written and any Non-Qualified child tags would by in that namespace. In case of the spring example above - the <beans> and <bean> element belong to the namespace http://www.springframework.org/schema/beans
     
  2.  Qualified Names
    The namespaces xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" and xmlns:util="http://www.springframework.org/schema/util" are qualified namespaces. It means any element that are prefix with xsi or util would be part of that respective namespace!
Did you spot where the namespace xsi is used in the example above?
Why do they matter?

In pretty simple terms the name of any XML element (referred as QName) comprises of the XML NameSpace + Local Name.
e.g. QName(Beans) = http://www.springframework.org/schema/beans/ + beans
This means two different XML element may have the same name in different Namespaces.

Namespaces in XML are the Java Equivalent of Packages!

That's XML Namespaces in nutshell1. Next time you look at some boiler plate XML - be sure to give it a second glance.

Foot Notes
  1. The XML Name Reference at w3.org

0 comments:

Post a Comment

Leave a thought, always good to hear :)