What are XML namespaces and why do I need them?

Dark navy cover card with the title 'What are XML namespaces and why do I need them?' in white and a green accent bar

XML namespaces attach a unique identifier, usually a URL, to element and attribute names, so names from different vocabularies can sit in one document without colliding. You declare them with an xmlns attribute. You need them whenever you mix XML formats (SVG inside XHTML, SOAP envelopes, Atom feeds with extensions) or when your code, XSLT or XPath has to pick out elements from a document that already declares one.

Why XML namespaces exist

XML namespaces exist because XML lets anyone invent element names, and popular names get reused. The element title alone appears in XHTML, SVG, RSS and Dublin Core, as the XML Namespaces FAQ points out. Drop two of those into one file and a program can't tell a page title from a book title.

A namespace fixes that by giving each name two parts: a namespace name (a URI) and a local name. title in the XHTML namespace and title in the Dublin Core namespace become two different names, even though they're spelled the same in the file.

New to the format itself? Start with what an XML file is.

How xmlns declarations work

An XML namespace is declared with a reserved attribute named xmlns or starting with xmlns:. The rules live in the W3C recommendation Namespaces in XML 1.0 (Third Edition), dated 8 December 2009.

It comes in two forms:

<!-- Prefixed: bind "dc" to a URI, then use dc: on names -->
<book xmlns:dc="http://purl.org/dc/elements/1.1/">
  <dc:title>Dune</dc:title>
</book>

<!-- Default: every unprefixed element inside is in this namespace -->
<svg xmlns="http://www.w3.org/2000/svg">
  <title>Logo</title>
</svg>
  • Prefixed declaration (xmlns:dc="..."): the prefix dc is shorthand for the URI. Only names written as dc:something are in that namespace.
  • Default declaration (xmlns="..."): every element without a prefix, on that element and inside it, belongs to the URI.

A declaration's scope is the element it sits on plus everything inside it, unless an inner element redeclares the same prefix or default. So different parts of one file can bind the same prefix to different URIs.

A namespace URI is an identifier that parsers compare as text; nobody downloads it. The SVG guide on namespaces says it plainly: namespace names are just strings, and URIs are used because they're unique, not to link anywhere. The FAQ adds that the URI isn't guaranteed to point to a schema or any document.

So http://www.w3.org/2000/svg works even though it isn't a page you'd read. A domain you own is just the cheap way to avoid a name someone else already took.

A few names are fixed by the spec:

Prefix or vocabulary Namespace URI
xml: (as in xml:lang) http://www.w3.org/XML/1998/namespace
xmlns: (declarations only) http://www.w3.org/2000/xmlns/
XHTML http://www.w3.org/1999/xhtml
SVG http://www.w3.org/2000/svg
MathML http://www.w3.org/1998/Math/MathML

The last three come from the createElementNS reference. Never declare the xmlns prefix yourself, and don't use it in element names.

When you actually need XML namespaces

You need XML namespaces when more than one vocabulary meets, or when a format you consume already uses them. You can skip them for a private, single-purpose file that nothing else will ever merge with.

  1. Mixed formats. SVG or MathML inside XHTML, a custom extension inside an Atom or RSS feed, metadata blocks in an office document.
  2. A standard requires them. XSLT stylesheets and XML Schema files both rely on namespaces to tell their own instructions apart from your data. Drop the xmlns and tools stop recognising the file.
  3. Elements built in code. In a browser, an SVG element built with createElement is an HTML element and won't draw. You need createElementNS with the SVG URI.
  4. XPath or XSLT queries. If the document declares a default namespace, your queries have to bind it, as the next section shows.

My take: if anyone else will read your new XML format, give it a namespace on day one. Adding one later renames every element and breaks every consumer's queries at once.

Why XPath returns nothing on a document with a default namespace

XPath returns no matches on many namespaced files because an unprefixed name in an XPath 1.0 query means "no namespace", while the document's elements are in the default namespace. Same spelling, different names.

Take this Atom feed:

<feed xmlns="http://www.w3.org/2005/Atom">
  <entry><title>Release notes</title></entry>
</feed>

The query /feed/entry/title finds nothing. Microsoft's support note for MSXML 6.0 describes exactly this: selectNodes and selectSingleNode return no matching nodes until you register the default namespace under a prefix. The fix is the same in every language:

const resolver = (p) => p === "a" ? "http://www.w3.org/2005/Atom" : null;
document.evaluate("/a:feed/a:entry/a:title", xmlDoc, resolver,
  XPathResult.FIRST_ORDERED_NODE_TYPE, null);

The prefix a exists only in your code. It doesn't have to match anything in the file, because matching happens on the URI.

Three namespace mistakes that break parsing and queries

Most namespace bugs come from treating the prefix or the URI as something it isn't.

  • Assuming attributes inherit the default namespace. They don't. The spec says an unprefixed attribute's namespace name always has no value. In <svg xmlns="..." width="10">, width has no namespace. Only a prefixed attribute such as xlink:href is namespaced.
  • A URI that's "close enough". URIs are compared as character strings and are identical only when every character matches. https:// instead of http://, a trailing slash, or different letter case each create a different namespace, and tools treat your elements as an unknown vocabulary.
  • Code that matches on the prefix. soap:Envelope and env:Envelope are the same element if both prefixes point to the same URI. Code that checks for the literal text soap: breaks the day a sender picks another prefix.

Two more spec rules: an empty string can't be a namespace name, and in version 1.0 you can't "undeclare" a prefix by setting it to "".

If a namespaced file fails to load at all, the cause is usually basic well-formedness, covered in fixing "XML parsing error: not well-formed".

What happens to namespaces when you convert XML to JSON

Namespaces have no equivalent in JSON, so converters either keep the prefix as part of the key ("dc:title") or drop it. Either way the URI binding is lost, and two prefixes for one URI end up as different keys.

That's the real limitation of converting namespaced XML: the JSON is fine for reading, but it won't round-trip back to the same XML. The browser-based XML viewer and formatter on this site parses with the browser's own DOMParser, so use it to check that the declarations are well-formed before you convert. For the conversion trade-offs in general, see how to convert XML to JSON and how XML attributes map to JSON.

FAQ

Does the namespace URL have to point to a real page?

No. A namespace name is an identifier, not a link. Parsers never fetch it, and nothing has to exist at that address. A URL is used because a domain you control makes the name unique.

Are attributes in the default namespace?

No. A default namespace declaration applies only to unprefixed element names. An unprefixed attribute has no namespace at all. To put an attribute in a namespace, give it a prefix.

Does the prefix name matter?

No. The prefix is a local shorthand for the URI. Two documents that bind different prefixes to the same URI produce the same element names. Code should match on the URI, not the prefix.

Why does my XPath return nothing when the XML has xmlns?

XPath 1.0 has no way to say "the default namespace", so an unprefixed name in the query only matches elements with no namespace. Bind your own prefix to the document's URI in your code and use it in the query.

Sources