XML namespace

The educational technology and digital learning wiki
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search


Learning goals
  • Understand why Namespaces are needed
  • Learn how to use namespace declarations
  • Learn how to create combined XHTML/SVG/MathML/etc documents
Moving on
Level and target population
  • Beginners
  • This tutorial provides a short overview about XML namespaces. It includes minimal knowledge needed for an XML class. Most parts also can be used in introductory web technologies class. Technical web authors also must understand namespaces, since they are used in XHTML and combined profiles.

XML namespaces have two purposes:

  1. Clearly identify a markup language and its version. Schema declarations like DTDs or XML Schema are not mandatory in many XML applications
  2. Allow to mix two or more languages in a single document.

XML Namespaces allow to fully/uniquely qualify XML element and attribute names to prevent confusing two elements that have the same name but mean different things. Various XML vocabularies (languages/applications) may be mixed. E.g. in a standards compliant web browser like Firefox or Opera you may include SVG and MathML code with the same XHTML page. But then we can run into naming conflicts, i.e. different vocabularies (DTDs) can use the same names for elements ! Namespaces are a W3C standard since Jan 1999. That means that namespaces have been introduced after XML has been invented.

Since DTDs are not mandatory for most W3C XML languages, the W3C requires namespace definitions within root elements, e.g. XHTML and SVG must include a namespace declaration:

The following was mandatory in for valide XHMTL 1.x files:

<html xmlns="http://www.w3.org/1999/xhtml">

Basically this statement says that within the html element all child elements belong to XHTML, unless they are explicitly part of another namespace.

The following example shows how to declare SVG files or fragments with an example (this is also valid for inclusion in HTML5)

<svg id="circle" height="200" xmlns="http://www.w3.org/2000/svg">
      <circle id="greencircle" cx="30" cy="30" r="30" fill="green" />

Standards involved

The Namespace standard:

Namespaces are identified with URIs

A URI is either a URL or a URN

Compound W3C documents

See also: The standards overview article. Most XML-based standards in education (e.g. IMS Content Packaging make heavy use of namespaces ! In addition most IMS and SCORM standards use XML Schema which are associated to XML contents via namespace declarations.


An example demonstrating the need for namespaces

Here is an XML fragment using title within a bibliography element:

 <title>A true story</title>
 <description>A real cool publication</description>

A 2nd XML fragment uses title in a employees record:

 <title>Dr. </title>
 <publications> ... </publications>

If these two XML fragments were added together, there would be a name conflict because both contain a <title>< element with different meaning. In one case we mean book title and in the other something like "none", PhD, etc.. A style-sheet would have to render these elements very differently. But we can solve this problem by adding prefixes, like this:

  <employees:title>Dr. </employees:title>
      <biblio:title>A true story</biblio:title>
      <biblio:description>A real cool publication</biblio:description>

A real world example

The The Open Packaging Format. Below is the content of an *.opf file that must be included within ePub "zip" file (a popular e-book format. It defines the structure of the book using assets and includes metadata.

OPF example copied with minor modifications from Wikipedia (nov 30 2010).

<?xml version="1.0"?>
<package version="2.0" 
  <metadata xmlns:dc="http://purl.org/dc/elements/1.1/" 
    <dc:title>Pride and Prejudice</dc:title>
    <dc:identifier id="BookId" opf:scheme="ISBN">123456789X</dc:identifier>
    <dc:creator opf:file-as="Austen, Jane" opf:role="aut">Jane Austen</dc:creator>
    <item id="chapter1" href="chapter1.xhtml" 
    <item id="chapter2" href="chaptertwo.xhtml" 
    <item id="stylesheet" href="style.css" 
    <item id="ch1-pic" href="ch1-pic.png" 
    <item id="myfont" href="css/myfont.otf" 
    <item id="ncx" href="book.ncx" media-type="application/x-dtbncx+xml"/>
  <spine toc="ncx">
    <itemref idref="chapter1" />
    <itemref idref="chapter2" />
    <reference type="loi" title="List Of Illustrations" 
               href="appendix.html#figures" />

This OPF file includes two namespaces:

Declaring namespaces

Formally speaking, an XML namespace is simply a collection of names (elements and attributes) of a markup vocabulary that can be uniquely identified

  1. Create or identify a namespace identifier you wish to use: An XML namespace is identified by a unique URI reference, usually a URL.
  2. The URL does need not point to anything on the Internet. It is just used as a unique string, i.e. a name
  3. Therefore if some namespace URLs below are broken there is absolutely nothing to worry about. However, most namespace identifiers actually point to a real web page that either provides an explanation or at least information about the organization/author that created the namespace. This means that if you plan to create your own namespaces, you should use the name of any webpage over which you have control.
  4. Make a namespace declaration within the element that belongs to this namespace, i.e. map a prefix of your choice to a unique URI.

There are two major variants of namespace use: prefixed namespaces and default ones.

(1) Namespace declaration for use with a prefix: declaring a namespace that will require use of prefixes for each element

 <prefix:element xmlns:prefix="URI">


 <html:html xmlns:html="http://www.w3.org/1999/xhtml">
   <html:head> ..... </html:head>

Each element below html:html that uses prefix "html:" will belong to Xhtml. Any other will not.

(2) Default namespace: declaring a default namespace for element and its children. I.e. these will not be prefixed.

 <element xmlns="URI"><


 <html xmlns="http://www.w3.org/1999/xhtml">


"Scoping" means "where does a declaration apply ?

The scope of an XML namespace declaration extends from the beginning of the start-tag in which it appears to the end of the corresponding end-tag, including all children. Most frequently, namespaces are declared in the document root.

XHMTL fragment example
<?xml version="1.0"?>
  <html:html xmlns:html='http://www.w3.org/1999/xhtml'>
      Moved to<html:a href='http://frob.example.com'>here.</html:a>

The scope of the XHMTL namespace declaration goes from <html:html> to </html:html>.

Example with 2 namespaces (both use URNs instead of URLs)
<?xml version="1.0"?>
<!-- both namespace prefixes are available throughout the XML fragment -->
<bk:book xmlns:bk='urn:loc.gov:books'
    <bk:title>Cheaper by the Dozen</bk:title>

Default namespaces

If most elements in an XML document belonged to the same namespace, it would be ugly to prefix each element name. Instead define a default namespace that applies to all non-prefixed elements and attributes. Syntax:

 <element xmlns="URI"> < ....

The default namespace applies to the element in which it was defined and all descendants of that element. But if a descendants has another default namespace defined on it, this new namespace definition overrides the previous one and becomes the default for that element and its descendants. Note that namespaces does not apply to attribute names ! This is a likely source of trouble for XSLT ...

XHTML default namespace example
<?xml version="1.0"?>
<!-- elements are in the HTML namespace by default -->
<html xmlns='http://www.w3.org/1999/xhtml'>
      <p>Moved to <a href='http://frob.example.com'>here</a>.</p>

Default namespace for a book vocabulary plus a namespace for ISBN example:

  <!-- unprefixed element types are from "books" -->
  <book xmlns='urn:loc.gov:books'
  <title>Cheaper by the Dozen</title>
A larger example of namespace scoping

It includes some XHTML whose namespace is declared within the "p" element.

<?xml version="1.0"?>
<!-- initially, the default namespace is "books" -->
<book xmlns='urn:loc.gov:books'
   <title>Cheaper by the Dozen</title>
   <!-- make HTML the default namespace for some commentary -->
      <p xmlns='http://www.w3.org/1999/xhtml'>
         This is a <i>funny</i> book!
XSLT namespace example

XSLT is a transformation language, i.e. programming language that allows to translate an XML content into another content (XML or other). XSLT instructions are prefixed with "xsl" here. Output produced is namespace-less here. See the XSLT tutorial for an introduction.

<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="page">
  <html> <head> <title> <xsl:value-of select="title"/> </title> </head>
  <body bgcolor="#ffffff"> <xsl:apply-templates/> </body>

<xsl:template match="title">
  <h1 align="center"> <xsl:apply-templates/> </h1>

<xsl:template match="content">
  <p align="center"> <xsl:apply-templates/> </p>

<xsl:template match="comment">
  <hr /> <xsl:apply-templates/>

Validation of composite documents

Validating documents that contain different namespaces are called composite or compound documents and validation is not always easy since combined DTDs may not exist. A validation standard for composite W3C vocabularies is currently under preparation (but may not happen ...). Usually, combined documents are produced by server-side programs for delivery and they are just well-formed (not attached to DTDs or other schemas)

You also may write DTDs that validate your own compound documents as we demonstrate in the following example.

A DTD rule with an extra namespace example

In this example, the "a" element and the "description" attribute belongs to the default namespace, but the href and type attributes belong to the xlink namespace. We declare the namespace in the root element, but also could have done it just for the "el" element. Note: Xlinks do not work in IE7/8.

<!ELEMENT link_list (el+)>
<!ATTLIST link_list xmlns:xlink CDATA #FIXED "http://www.w3.org/1999/xlink">
<!ATTLIST el description CDATA #IMPLIED
          xlink:href CDATA #REQUIRED
          xlink:type CDATA #FIXED "simple" >

See the DTD tutorial for details.

An XML example file
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE link_list SYSTEM "link_list.dtd">
<?xml-stylesheet href="link_list.css" type="text/css" ?>
 <link_list xmlns:xlink="http://www.w3.org/1999/xlink">
    <el description="verified"
        xlink:href="http://www.webster.ch/">Webster Geneva</el>
    <el xlink:href="http://www.webster.edu/"

Namespaces for documents

Client-side XML web languages and namespaces overview

The W3C defines several Internet languages and for which namespace declarations are mandatory (even if you use them "standalone", i.e. not in composite documents.

Some W3C languages
Name Namespace URL Explanation
XSLT http://www.w3.org/1999/XSL/Transform XSL - Transformations
XSL-FO http://www.w3.org/1999/XSL/Format XSL - Formatting
XML Schema http://www.w3.org/2001/XMLSchema XML grammar definition language
SVG http://www.w3.org/2000/svg Scalable Vector Graphics
RDF http://www.w3.org/1999/02/22-rdf-syntax-ns Resource Description Format
SMIL 2.0 http://www.w3.org/2001/SMIL20/ Synchronized Multimedia Integration Lang.
VoiceXML 2.0 http://www.w3.org/2001/vxml Synthesized voice
XLink http://www.w3.org/1999/xlink" XML Linking Language
XForms http://www.w3.org/2002/xforms Next generation of HTML forms.
XHTML http://www.w3.org/1999/xhtml XML-based HTML variant
MathML http://www.w3.org/1998/Math/MathML Mathematical markup language

Some of these languages (e.g. SMIL, MathML, SVG, X3D) need special clients for display. Others are transducers or helpers, i.e. are used to define, style, transform and process XML contents

RDF namespace

RDF-based languages are very prolific and add to the complexity of semantic web initiatives

See 100 most common RDF namespaces

Other Document standards

Each of the following usually packages a document as zip file. Inside the zip, you will find several files using several XML languages.

Compound documents

Combining various content delivery formats is the future (also on cell phones). For example, XHTML-formatted content can be augmented by SVG objects or mathematical formula.

Examples of possible Compound Document profiles
  • XHTML + SVG + MathML
  • XHTML + XForms
  • XHTML + VoiceML

The W3C is working on a generic Compound Document by Reference Framework (CDRF) that defines a language-independent processing model for combining arbitrary document formats ...

Web browser caveats
  • IE doesn't support natively most XML W3C "content" languages (e.g. SVG, MathML), but implements a version of SMIL, called "Timed Text". Firefox supports static SVG and MathML. Both implement RSS


  • Use a browser that is more advanced (e.g. Firefox, Opera, Chrome) or specialized players (e.g. Realplayer for SMIL)
  • For HTML + SVG + MathML, use HTML5
  • Call your files *.xml (often helps if you use IE)
  • For some formats you may install plugins or extensions in your web browser and then use a more indirect method to assemble contents, i.e. <object> or <iframe>. This will work with most browsers if you have the right plugin (SVG in this case) installed.
<iframe src="hello-svg.svg" height="300" width="80%" frameborder="0">
... Sorry you need an SVG plugin ...

XHTML + other vocabularies

XHTML / MathML example
<?xml version="1.0" encoding="iso-8859-1"?>
<xhtml:html xmlns:xhtml="http://www.w3.org/1999/xhtml">
    <xhtml:h1>A Compound Document</xhtml:h1>
    <xhtml:p>A simple formula using MathML in XHTML.</xhtml:p>
    <mathml:math xmlns:mathml="http://www.w3.org/1998/Math/MathML">
         <mathml:msqrt> <mathml:mn>49</mathml:mn> </mathml:msqrt>

MathML doesn't natively work with IE 6/7/8. But there are workarounds. See the MathML article for some more information about MathML and dealing with IE.

Xlink example

XLink was supposed to replace all linking constructs in the W3C languages. It is adopted by SVG, X3D, but not by XHTML 2 which introduces its own linking constructs. XML-capable browsers are also supposed to implement this (Firefox, but not IE)

Example - Story grammar that implements XLink for an A element
<?xml version="1.0" encoding="ISO-8859-1" ?>
<STORY xmlns:xlink="http://www.w3.org/1999/xlink">
  <Title>The Webmaster</Title>
  <INFOS> <Date>30 octobre 2003 - </Date>
  <Author>DKS - </Author>
  <A xlink:href=http://jigsaw.w3.org/css-validator/check/referer
     xlink:type="simple">CSS Validator</A>
SVG example
  • Most browsers (i.e. all major browser except IE8) can handle SVG. However, some only implement SVG 1.0 and most only static SVG. As of, only Opera implemented the so-called SMILE tags.
  • Alternatively, use HTML and read the using SVG with HTML5 tutorial

XHTML with embedded SVG tags (tested with Firefox)

<?xml version="1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" >

<html xmlns="http://www.w3.org/1999/xhtml"  
  <title>SVG within XHTML Demo</title>
  <h1>SVG within XHTML Demo</h1>

  <p> You can embed SVG into XHTML, provided that your browser
  natively implements SVG. E.g. Firefox 1.5+ supports most of static
  SVG.  </p>

  The SVG part starts below <hr />

  <svg xmlns="http://www.w3.org/2000/svg" version="1.1" 
       width="400" height="300">
   <!-- a small rectangle -->
   <rect x="50" y="50" rx="5" ry="5" width="300" height="100"
   <!-- a text in the same place -->
   <text x="55" y="90" style="stroke:#000099;fill:#000099;font-size:24;">
    HELLO dear reader

  <hr />
  The SVG part ended above

SVG within HTML5. This also should work with very old browsers (e.g. IE 6 and FF 1) plus the now unavailable SVG plugin from Adobe.

<!DOCTYPE html>
  <head> <title>HELLO SVG with an iframe</title> </head>
     <h1>HELLO SVG with an iframe</h1>
        Here is an embeded SVG scene using iframe. 
	<iframe src="hello-svg.svg" height="200" width="80%" frameborder="0">

In the following example, the SVG file is a standard stand-alone SVG file

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN"
<svg xmlns="http://www.w3.org/2000/svg">
   <rect x="50" y="50" rx="5" ry="5" width="300" height="100"
   <text x="55" y="90" style="stroke:#000099;fill:#000099;font-size:24;">
   HELLO dear reader

Combining XHTML with your XML

It sometimes can be practical to combine your own XML contents with XHTML, because HTML offers easy-to-use functionality like image inclusions or links. Note however that in practice this feature is not often used since:

  • XSLT stylesheets allow transformations of XML data into XHTML. The stylesheet will contain the extra HTML and the result displayed usually will be all HTML and will be easier to manage with CSS.
  • The way browsers implement this feature is not really stable
  • Since HTML5 is now dominant, people cannot remember the potential of XHTML.
XHTML with some XML included, using CSS for styling
  • Tested with Firefox 2.x (works) and IE 7 (CSS doesn't work, I don't know why ...)


  1. Define a namespace for the included XML content
  2. Attach a CSS stylesheet with an XML processor instruction. Else, users will not see the contents of your XML.
  3. Your file must be understood as "XML", e.g. call it something.xhtml or something.xht or something.xml. If you use IE7/8 it must be something.xml, since IE doesn't support XHTML). Do not call your file something.html or something.htm !!

XHTML with some cooking XML included (file cooking.xhtml):

<?xml version="1.0" ?>
<?xml-stylesheet type="text/css" href="cooking.css"?>

<html xmlns="http://www.w3.org/1999/xhtml"
    <title>A Compound XHTML-XML Document</title>
    <!-- this should work with IE but doesn't, maybe IE6 ? -->
    <link href="dolores.css" type="text/css" rel="stylesheet"/>


    <h1>A Compound XHTML-XML Document</h1>

    <p>Contains a cooking recipee written down by R. Dolores for a
    COAP 2180 CSS exercise. Everything below the line is XML styled
    with a CSS stylesheet</p> <hr/>

      <re:recipe_name>Cold Salmon in Creamy Spiced Sauce</re:recipe_name>
      <re:recipe_author>Hilaire Walden</re:recipe_author>
      <re:meal_type>Fish and Shellfish</re:meal_type>
	<re:ingredient>1/2 teaspoon finely crushed cumin seeds</re:ingredient>
	<re:ingredient>1 teaspoon chilli powder</re:ingredient>
	<re:ingredient>salt and freshly ground black pepper</re:ingredient>
	<re:ingredient>2 tablespoons olive oil</re:ingredient>
	<re:ingredient>2 cloves garlic, crushed</re:ingredient>
	<re:ingredient>1.25 cm (1/2 in) fresh ginger root, finely
	<re:ingredient>4 pieces salmon fillet, skinned</re:ingredient>
	<re:ingredient>125 ml (4 fl oz / 1/2 cup) double (heavy)
	<re:ingredient>250 ml (8 fl oz / 1 cup) thick plain
	<re:ingredient>large pinch of saffron threads, toasted and
  	<re:ingredient>seeds from 6 cardamom pods, toasted and finely
  	<re:ingredient>coriander (cilantro) to garnish</re:ingredient>
	<re:direction>Mix together the cumin seeds, chilli powder and
	pepper and rub into the fish.</re:direction>
	<re:direction>Heat the oil in a frying pan, add the garlic and
	ginger and heat until they sizzle.</re:direction>
	<re:direction>Add the salmon fillets and fry until they start
	to colour (about 15-20 seconds on each side).</re:direction>
	<re:direction>Stir in the cream, yogurt, saffron, cardamom and
	<re:direction>Adjust the heat so that the sauce is just
	bubbling and cook, turning the fish once, until the flesh just
	flakes when tested with the point of a sharp knife (about 3-4
	minutes each side).</re:direction>
	<re:direction>Transfer the fish to a shallow dish. Boil the
	sauce until it has reduced and thickened, pour over the fish
	and leave to cool.</re:direction>
        <re:direction>Cover the dish and chill until 15-20 minutes
        before serving.</re:direction>
	<re:direction>Garnish with coriander (cilantro).</re:direction>

     <re:preparation_time>15 minutes</re:preparation_time>

       <re:document_author>Hilaire Walden</re:document_author>
       <re:source>Easy to Cook, Hot &amp; Spicy</re:source>

Combining your XML with XHTML

Works with Firefox 1x/2x and IE7 (probably also with IE6).

  • An HTML namespace is declared in the root element and we use it twice (for the img and a tags).
  • Btw this is a trick to get around non-implementation of the xlink standard in IE.
<?xml version="1.0" ?>
<?xml-stylesheet href="xml_plus_xhtml.css" type="text/css"?>
<page xmlns:html="http://www.w3.org/1999/xhtml" updated="jan 2007">
 <title>Hello friend</title>
   <!-- we use an HTML tag below to include a picture -->
   <html:img src="photo.jpg"/>
   <item price="10"> White plate </item> 
   <item price="20"> Gold plate </item> 
   <item price="15"> Silver plate </item> 

 <comment> Written by <html:a href="http://tecfa.unige.ch/DKS">DKS/Tecfa</html:a>
 , feb 2007 </comment>

XSLT transformations of compound documents

Transforming XML files that include namespace (including just default namespaces that do not use prefixes) requires that you prefix each XPath "component". For more information, see: