In this tutorial you will learn about the XML Namespace and its application with practical example.
XML Namespace helps us to prevent conflict that may occur due to the naming of the elements.
As XML allow us define our custom tags there is always the chances of having element name exactly same as other element in another XML document.This is okay if we are not using both documents together. But in case if we want to include the content of both documents, what happen? we’ll run into problem due to name conflict. Here we are having two different elements, with different use but both are having same name.
Lets take look at below XML document
1 2 3 4 5 6 7 |
<inbox> <message id="1"> <from>John</from> <subject>Test Message 1</subject> <body>Hello John!</body> </message> </inbox> |
And now if we want to include the above XML Document in below HTML Document
1 2 3 4 5 6 7 8 9 10 11 |
<html> <head> <title>Inbox</title> </head> <body> <p>Inbox</p> (XML content goes here) </body> </html> |
Now if we try to include above XML Document in the the above HTML documents we’ll run into a problem. Because they both have an element called body. One is the body of the message and other is the body of the HTML Document.
By creating a namespace for the XML document. We can solve this problem.
XML Namespace Example
Lets change above XML Document using namespace
1 2 3 4 5 6 7 |
<ib:inbox xmlns:ib="http://w3school.in/inbox/namespace/"> <ib:message id="1"> <ib:from>John</ib:from> <ib:subject>Test Message 1</ib:subject> <ib:body>Hello John!</ib:body> </ib:message> </ib:inbox> |
By adding xmlns:{prefix} attribute to the root element and assigning it a unique value which is usually in the form of a Uniform Resource Identifier (URI). It defines a namespace.
Now in this way we have created a namespace and we have added ib as prefix to our XML Element names.
Now when we call both documents together XML processor will have two different body element.