Introduction
Namespace in XML gives uniqueness to the elements/attributes.
Namespace in XML can be compared to packages in java or namespaces in DotNET.
Namespace in a xml document are declared using attribute xmlns and any prefix character.
Syntax - xmlns:prefix="URI"
here, xmlns stand for XML Namespace
and prefix can be anycharacters
Example -
<?xml version="1.0"?>
<root xmlns:nm1="http://www.web1.com"
xmlns:nm2='http://www.web2.com">
<nm1:elem1>Element 1</nm1:elem1>
<nm2:elem2>Element 2</nm2:elem2>
<nm1:elem3>Element 3</nm1:elem3>
<nm2:elem4>Element 4</nm2:elem4>
</root>
Namespace in XML gives uniqueness to the elements/attributes.
Namespace in XML can be compared to packages in java or namespaces in DotNET.
Namespace in a xml document are declared using attribute xmlns and any prefix character.
Syntax - xmlns:prefix="URI"
here, xmlns stand for XML Namespace
and prefix can be anycharacters
Example -
<?xml version="1.0"?>
<root xmlns:nm1="http://www.web1.com"
xmlns:nm2='http://www.web2.com">
<nm1:elem1>Element 1</nm1:elem1>
<nm2:elem2>Element 2</nm2:elem2>
<nm1:elem3>Element 3</nm1:elem3>
<nm2:elem4>Element 4</nm2:elem4>
</root>
All the elements that has prefix of nm1 belongs to the namespace http://www.web1.com
All the elements that has prefix of nm2 belongs to the namespace http://www.web2.com
Default Namespace
Namespace in XML can be explicitly declared as above or we can assign default namespace as shown below.
Elements without any prefix characters belongs to the default namespace.
<?xml version="1.0"?>
<root xmlns="http://www.web1.com">
<name1>Alpha<name1>
<name2>Bravo<name2>
<name3>Charlie<name3>
<name4>Echo<name4>
</root>
Namespace Declaration
There are two places where a namespace can be declared
1)At root level
2)At element level
Method 1 : At root level - In this method we declare all the namespaces in the root element of the XML.
<?xml version="1.0"?>
<root xmlns:T="http://Technical/"
xmlns:NT="http://NonTecNTnical/">
<T:Employee>
<T:ID>1</T:ID>
<T:Name>Alpha</T:Name>
</T:Employee>
<NT:Employee>
<NT:ID>1</NT:ID>
<NT:Name>Bravo</NT:Name>
</NT:Employee>
</root>
Method 2 : At element level - In this method we declare the namespaces in the elements of the XML.
<?xml version="1.0"?>
<root>
<T:Employee xmlns:T="http://Technical/" >
<T:ID>1</T:ID>
<T:Name>Alpha</T:Name>
</T:Employee>
<NT:Employee xmlns:NT="http://NonTecNTnical/">
<NT:ID>1</NT:ID>
<NT:Name>Bravo</NT:Name>
</NT:Employee>
</root>