Friday, January 6, 2012

Namespace vs Targetnamespace

 Before going to Namespace vs Targetnamespcace lets see few basics

What is xml: A document with some user defined tags (element) and attributes.
What is xsd: A file which forces some rules on xml. In other words it defines the structure of xml like what all tags can appear in xml, parent tags, child tags and their attributes blah blah...

  Let say I have three friends A, B, C. They all have written xsds say A.xsd, B.xsd and C.xsd. Definitely they have defined few rules in those xsd. I want to use all these xsd and write an xml document. Definitely my xml document would be referring to those xsds.

What if A, B and C all has defined a tag X in their xsds. How would I write that tag in my xml? Which xsd would be referred.

To solve this problem they all must make sure that they have different tags. That is not possible as every xsd in this world can't think of a new tag. (Everybody needs that <Name> tag :)). Other solution could be to ask them to provide some unique prefix with their tags. For example A can say use prefixA with my tags, B can say use prefixB with my tag and C can say prefixC.

Defining a prefix for your tags is called targetnamespcace. Again we need to make sure that these prefixes are unique. That is why its advised to use http://compname/somthing-that-can-distinguish-within-company such uniquely identified name. This is the reason target-namespace etc comes in xsd generally not in normal xml as they don't define tags and their prefix.

Now I should write <prefixA:X> while referring X tag of A's xsd. Similarly <prefixB:X> and <prefixC:X>

Now there is only one problem I don't like these prefixes, they are very long specially if someone ask me to write <http://sanjeev.chauhan/xyz/abc:X>

xml provides a way to alias these big names. This aliasing is called namespace.
 I just need to write following line (namespcace) in my xml once at the top
xmlns:c="prefixC"



Then after I can simply use <c:X> to refer tag X tag defined in C.xsd.


(I don't know whether I understood it right or not but that is what I understood... :) )



Disclaimer: Any views or opinions presented in this blog are solely those of the author and do not necessarily represent those of the company.