CodeMIRAI
0 XP

Namespaces

2 min read 3 runnable examples Quiz included

Different XML vocabularies often use the same names. A <title> in a book catalogue and a <title> in a web page mean different things, and so do a <table> of data and a <table> of furniture. Namespaces keep them apart.

The problem

XML
<!-- xpath: //table -->
<order>
  <table>
    <tr><td>Desk lamp</td><td>2</td></tr>
  </table>
  <table>
    <name>Oak dining table</name>
    <seats>6</seats>
  </table>
</order>

Two very different table elements, and nothing to tell a program which is which.

Prefixes and xmlns

XML
<!-- xpath: //h:table -->
<!-- xpath: //f:table/f:name -->
<order xmlns:h="http://www.w3.org/1999/xhtml"
       xmlns:f="https://example.com/furniture">
  <h:table>
    <h:tr><h:td>Desk lamp</h:td><h:td>2</h:td></h:tr>
  </h:table>
  <f:table>
    <f:name>Oak dining table</f:name>
    <f:seats>6</f:seats>
  </f:table>
</order>
  • xmlns:f="https://example.com/furniture" declares a prefix, f, for a namespace.
  • f:table then means "the table from the furniture namespace".
  • A namespace name is a URI, usually a web address its owner controls. It's only a unique label: nothing is downloaded from it, and it doesn't have to lead anywhere.

The runner understands the prefixes declared in the document, so //h:table and //f:table/f:name find the right elements.

The default namespace

XML
<!-- xpath: //book -->
<!-- xpath: //*[local-name()='book']/*[local-name()='title'] -->
<!-- xpath: //bk:book/bk:title -->
<library xmlns="https://example.com/books" xmlns:bk="https://example.com/books">
  <book><title>Clean Code</title></book>
  <book><title>Refactoring</title></book>
</library>

xmlns="...", without a prefix, sets the default namespace: every unprefixed element inside belongs to it. That catches out many XPath users. In XPath 1.0, an unprefixed name means "an element in no namespace", so //book matches nothing here. Either bind a prefix to the same URI, as bk: does, or match on local-name().

The prefix is only shorthand

What identifies a namespace is its URI, not its prefix. These two elements are exactly the same element:

XML
<bk:title xmlns:bk="https://example.com/books">Dune</bk:title>
<x:title xmlns:x="https://example.com/books">Dune</x:title>

Namespaces you'll meet

Usual prefixNamespace URIUsed for
(default)http://www.w3.org/2000/svgSVG graphics
(default)http://www.sitemaps.org/schemas/sitemap/0.9sitemaps for search engines
xshttp://www.w3.org/2001/XMLSchemawriting XML Schemas
xsihttp://www.w3.org/2001/XMLSchema-instancepointing a document at its schema
soaphttp://schemas.xmlsoap.org/soap/envelope/SOAP web service messages

CodeMIRAI's own sitemap.xml, which tells search engines about every lesson, uses the sitemap namespace as its default.

Finished this lesson?Mark it complete to earn +20 XP and move your progress on.