How to use Namespaces in XML

In this article I am going to tell about XML Namespaces.
  • 2306

Definition

XML Namespaces provide a method to avoid confliction in elements name. We use this because in XML, elements name are defined by the programmers. This often result in conflict when trying to bind XML document with any other XML application.

Supporting Browsers

Internet Explorer, Mozilla Firefox, Google Chrome, Safari and Opera are the supporting browsers.

Example

Imagine we have a XML document containing  list of cd's.
 

<cds>

    <cd>

         <title>waka waka</title>

         <singer>shakira</singer>

    </cd>

    ....

</cds>


And imagine we want to combine it with this HTML page.
 

<html>

    <head>

         <title>super music</title>

    </head>

         <body>Here's the list of super music

            <p>

               (XML content comes here)

            </p>

    </body>

    ....

</html>

We will encounter a problem if we try to combine the above documents. Because they both have an element called title. One is the title of the cd, the other is the title of the HTML page. We have a name conflict. For preventing this confliction we create a namespace for the XML document.

Using the above example, we could change the XML document to look something like this:

<ms:cds xmls:ms="http://supermusic.com/cd_sp">

    <ms:cd>

         <ms:title>waka waka</ms:title>

         <ms:singer>shakira</ms:singer>

    </ms:cd>

    ....

</ms:cds>

We have added the xmlns:{prefix} attribute to the root element. We have assigned this attribute a unique value. This unique value is in the form of a URI. This defines the namespace.

And, now the namespace has been defined, we have added a ms prefix to our element names.

You may read more articles about XML here

Ask Your Question 

Got a programming related question? You may want to post your question here

Programming Answers here

© 2020 DotNetHeaven. All rights reserved.