Namespaces
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
<!-- 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
<!-- 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:tablethen means "thetablefrom 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
<!-- 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:
<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 prefix | Namespace URI | Used for |
|---|---|---|
| (default) | http://www.w3.org/2000/svg | SVG graphics |
| (default) | http://www.sitemaps.org/schemas/sitemap/0.9 | sitemaps for search engines |
xs | http://www.w3.org/2001/XMLSchema | writing XML Schemas |
xsi | http://www.w3.org/2001/XMLSchema-instance | pointing a document at its schema |
soap | http://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.