Bookmark and Share

XML Namespace

XML was designed to be a very robust markup language that could be used in many different applications. However, with XML being able to communicate between so many different platforms, there is one problem that tends to occur.

Advertise on Tizag.com

XML Element Overlap

When you are creating new elements, there is the chance that the element's name already exists. Imagine someone was creating a health-related XML document that included XHTML (that's HTML that is also valid XML).

XML Code:

<?xml version="1.0" encoding="ISO-8859-15"?>
<html>
<body>
<p>Welcome to my Health Resource</p>
</body>

<body>
<height>6ft</height>
<weight>155 lbs</weight>
</body>

</html>

Here, we have two very different elements that want to use the same name: body. The solution to this problem is to create XML Namespaces, which will differentiate between these two similarly named elements!

XML Namespace Syntax

The XML namespace is a special type of reserved XML attribute that you place in an XML tag. The reserved attribute is actually more like a prefix that you attach to any namespace you create. This attribute prefix is "xmlns:", which stands for XML NameSpace. The colon is used to separate the prefix from your namespace that you are creating.

As we mentioned in our XML Attribute Lesson, every XML attribute must be set equal to something. xmlns must have a unique value that no other namespace in the document has. What is commonly used is the URI (Uniform Resource Identifier) or the more commonly used URL.

To rectify the overlap in our health XML document, we will be using the W3C's XHTML URL and a made up URI for our second body element. Both the namespace attribute and its use in our document has been highlighted in red.

XML Code:

<?xml version="1.0" encoding="ISO-8859-15"?>
<html:html xmlns:html='http://www.w3.org/TR/xhtml1/'>
<html:body>
<html:p>Welcome to my Health Resource</html:p>
</html:body>

<health:body xmlns:health='http://www.example.org/health'>
<health:height>6ft</height>
<health:weight>155 lbs</weight>
</health:body>

</html:html>

By placing a namespace prefix before our elements, we have solved the overlapping problem!

If you are feeling inquisitive, feel free to check out W3C's Namespace Document for a very in-depth look at XML namespaces. Be warned; it is quite long and dry!

Bookmark and Share




Download Tizag.com's XML Book

If you would rather download the PDF of this tutorial, check out our XML eBook from the Tizag.com store.

Found Something Wrong in this Lesson?

Report a Bug or Comment on This Lesson - Your input is what keeps Tizag improving with time!

Advertise Here

More Tutorials!
Microsoft Office Tutorials Artist Tutorials