Namespaces in XML

Namespaces in XML primary purpose to a distinguish between duplicate element and attribute names.

XML data has to be exchanged between several application.

Same tag name may have different meaning in different application. So It's create confusion on exchanging documents.

Specifying prefix name to an element or attribute names to avoid this confusion.


XML Namespaces

  • Elements and attributes name along with namespace have exactly one colon.

  • Colon before text prefix name and colon after text element or attribute name.

  • Each and every prefix name is associated with one URI.

  • Prefix name associated with the same URI are in the same namespace.

  • Full qualified name including prefix, colon is called the XML qualified name.

Prefixes are bind to a namespace URI using xmlns:prefix attribute to the prefixed element.

 <r:student xmlns:r="">

Bindings prefixes scope within the element (starting element to a closing element).

 <r:student xmlns:r="">   <!--      Scope within this element.     prefix r is associated with the xml namespace   -->  </r:student>

Name Conflicts Example

Following example XML data for storing student marks,


 <student>   <result>     <name>Opal Kole</name>     <sgpa>8.1</sgpa>       <cgpa>8.4</cgpa>       </result>   <cv>     <name>Opal Kole</name>       <cgpa>8.4</cgpa>       </cv> </student>

Above XML document both <result> and <cv> have the same <cgpa> element, so XML parser doesn't know which one is parse.

That's why XML namespaces is use for mapping between an element prefix and a URI.

XML namespace URI not a point to a information about the namespace but they are identify unique elements.

Convert the Name Conflict to XML Namespaces

We are specify prefix name as per different element.

 <s:student>   <r:result>     <r:name>Opal Kole</r:name>     <r:sgpa>8.1</r:sgpa>       <r:cgpa>8.4</r:cgpa>       </r:result>   <res:cv>     <res:name>Opal Kole</res:name>       <res:cgpa>8.4</res:cgpa>       </res:cv> </s:student>

xmlns attribute with XML namespaces

Specify all XML namespaces within the root element. Specification given for the that element is valid for all element occurring within scope.

The namespace declaration Syntax: xmlns:prefix_name="URI".

 <s:student xmlns:s=""            xmlns:res="">   <r:result>     <r:name>Opal Kole</r:name>     <r:sgpa>8.1</r:sgpa>       <r:cgpa>8.4</r:cgpa>       </r:result>   <res:cv>     <res:name>Opal Kole</res:name>       <res:cgpa>8.4</res:cgpa>       </res:cv> </s:student>