Conceptadvanced
XML namespaces
Also called Namespaces in XML, xmlns.
An XML namespace is a URI that qualifies element and attribute names, so that two vocabularies can use the same local name in one document without a clash.
Idea
An XML document can mix elements from more than one vocabulary. A book catalog can use its own elements for the books, the Dublin Core elements for the metadata and the XHTML elements for a description. Two vocabularies can use the same name for different things, for example title for the title of a book and title for the title of an HTML page. A program must know which title it has.
Namespaces in XML, a W3C Recommendation, solves this problem. "An XML namespace is identified by a URI reference".1 Each element and attribute name is a pair: "An expanded name is a pair consisting of a namespace name and a local name."1 In the text, a short prefix stands for the URI, so the document says m:lang and not the full URI each time. The prefix is only a local abbreviation. The expanded name is the real name.
The motivation is modularity: "if such a markup vocabulary exists which is well-understood and for which there is useful software available, it is better to re-use this markup rather than re-invent it."1
How it works
A namespace declaration is an attribute. The attribute xmlns:p="URI" binds the prefix p to the URI. The attribute xmlns="URI" sets the default namespace. The document below uses both.
<catalog xmlns="urn:example:books" xmlns:m="urn:example:meta">
<book id="b1" m:lang="en">
<title>Tide tables</title>
<price xmlns="urn:example:money" currency="EUR">32.18</price>
</book>
</catalog>
The rules that give each name its namespace are these:
- Scope. A declaration applies from the start tag where it appears to the end of that element, "excluding the scope of any inner declarations with the same NSAttName part".1 In the example,
pricedeclares a new default namespace, sopriceis inurn:example:money, andtitleis still inurn:example:books. - Prefixed names. An element or attribute name with a prefix is in the namespace that the prefix is bound to.
m:langis the attributelanginurn:example:meta. A prefix that has no declaration in scope is an error. - Unprefixed elements. "A default namespace declaration applies to all unprefixed element names within its scope."1
catalog,bookandtitleare inurn:example:books. - Unprefixed attributes. "Default namespace declarations do not apply directly to attribute names".1 "The namespace name for an unprefixed attribute name always has no value."1 So
idandcurrencyare in no namespace, even though their elements are in a namespace. - Undeclaring. The attribute
xmlns=""removes the default namespace for an element and its contents.1 A prefix cannot be undeclared in Namespaces in XML 1.0.
The two prefixes xml and xmlns are reserved. "The prefix xml is by definition bound to the namespace name http://www.w3.org/XML/1998/namespace."1 It is the namespace of the attributes xml:lang and xml:space. The prefix xmlns is only for declarations, and a document must not declare it.1
The namespace name is an identifier, not an address. It "SHOULD have the characteristics of uniqueness and persistence. It is not a goal that it be directly usable for retrieval of a schema (if any exists)."1 A parser never fetches the URI. A URN such as urn:example:books and a URL such as http://www.w3.org/1999/xhtml work in the same way. "The empty string, though it is a legal URI reference, cannot be used as a namespace name."1
Two namespace names are the same only when they are the same string. "The comparison is case-sensitive, and no %-escaping is done or undone."1 http://example.com/a and HTTP://example.com/a are two different namespaces, though they are the same web address.
Namespaces change the rules of uniqueness of attributes. A tag must not have two attributes with the same expanded name. "This constraint is equivalent to requiring that no element have two attributes with the same expanded name".1 So a:x and b:x are an error when the prefixes a and b are bound to the same URI.
The specification is a layer on top of XML 1.0. XML 1.0 itself only reserves the colon for this use: "authors should not use the colon in XML names except for namespace purposes, but XML processors must accept the colon as a name character."2 A parser that is not namespace-aware sees m:lang as one name with a colon in it.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Standard library | |
| C++ | Library | The C++ standard library has no XML parser. Alternative: The C libraries libxml2 and Expat; pugixml leaves prefixes in the names and does not resolve namespaces. |
| Java | Standard library | |
| C | Library | ISO C has no XML functions. Alternative: Libxml2 (the field ns of each node) or Expat (XML_ParserCreateNS). |
| C# | Standard library | |
| JavaScript | Library | Node.js has no built-in XML parser; in browsers, the DOM of DOMParser has namespaceURI and localName on each element and getElementsByTagNameNS. Alternative: A package such as @xmldom/xmldom, which implements the DOM namespace methods. |
| TypeScript | Library | TypeScript has the same runtime as JavaScript; Node.js has no built-in XML parser. Alternative: A package such as @xmldom/xmldom, which implements the DOM namespace methods. |
| Go | Standard library | |
| Rust | Library | The Rust standard library has no XML parser. Alternative: The crate quick-xml has a namespace-aware reader, and roxmltree gives each node a namespace and a local name. |
| Kotlin | Library | The Kotlin standard library has no XML; on the JVM a program can use the JAXP classes of Java, as in the Java example. No example file exists because kotlinc is not installed. Alternative: The JAXP API of the Java platform. |
| SQL | Native | SQL/XML has the clause XMLNAMESPACES to declare namespaces in XMLELEMENT and XMLTABLE; SQLite has no XML functions. |
| Bash | Library | Bash has no XML parser. Alternative: Xmllint --xpath with local-name(), or xmlstarlet sel with -N to bind a prefix. |
| PowerShell | Standard library | Select-Xml takes a -Namespace hash table that binds prefixes for its XPath query; no example file because PowerShell is not installed on the machine that recorded the examples. |
| HTML | Does not apply | The HTML syntax has no namespace declarations; the HTML parser puts the elements in the XHTML namespace, and the svg and math elements in their own namespaces. |
| CSS | Does not apply | CSS has the @namespace rule for selectors on XML documents, but no data to parse. |
| Regular expressions | Does not apply | A regular expression cannot resolve the scope of namespace declarations. |
The XML libraries of each language give the expanded name in their own form. The Python example below shows the Clark notation {namespace}local of ElementTree.3
import xml.etree.ElementTree as ET
first = ET.fromstring('<x:item xmlns:x="urn:example:books"/>')
second = ET.fromstring('<item xmlns="urn:example:books"/>')
third = ET.fromstring('<item xmlns="urn:Example:books"/>')
print(first.tag, second.tag, first.tag == second.tag)
print(third.tag, first.tag == third.tag)
try:
ET.fromstring('<x:item/>')
except ET.ParseError as error:
print("ParseError:", error)
{urn:example:books}item {urn:example:books}item True
{urn:Example:books}item False
ParseError: unbound prefix: line 1, column 0
The first two documents use a prefix and a default namespace, and they give the same expanded name. The third differs only in the case of one letter, and it is a different namespace. The last document uses a prefix with no declaration, and the parser rejects it.
| Language | Expanded name | Find by namespace |
|---|---|---|
| Python | the string {uri}local3 |
find("p:book", {"p": uri}) |
| Go | xml.Name{Space, Local}4 |
the struct tag xml:"uri local" |
| Java | getNamespaceURI() and getLocalName() on a namespace-aware DOM5 |
getElementsByTagNameNS(uri, local) |
| C# | XName, made with XNamespace + "local"6 |
Element(ns + "book") |
The Java DocumentBuilderFactory is not namespace-aware by default: "By default the value of this is set to false".5 A program must call setNamespaceAware(true), or the parser treats m:lang as a name with a colon and gives no namespace. The example files show each language.
import xml.etree.ElementTree as ET
text = """<catalog xmlns="urn:example:books" xmlns:m="urn:example:meta">
<book id="b1" m:lang="en">
<title>Tide tables</title>
<price xmlns="urn:example:money" currency="EUR">32.18</price>
</book>
</catalog>"""
root = ET.fromstring(text)
book = root[0]
print(root.tag)
print(book.attrib)
for child in book:
print(child.tag, child.attrib)
ns = {"b": "urn:example:books", "money": "urn:example:money"}
print(root.find("b:book/b:title", ns).text)
print(root.find("b:book/money:price", ns).text)
print(root.find("book"))
print(ET.tostring(book[0], encoding="unicode").strip())
{urn:example:books}catalog
{'id': 'b1', '{urn:example:meta}lang': 'en'}
{urn:example:books}title {}
{urn:example:money}price {'currency': 'EUR'}
Tide tables
32.18
None
<ns0:title xmlns:ns0="urn:example:books">Tide tables</ns0:title>
- Verdict: stdlib. ElementTree writes each expanded name in the Clark notation
{namespace}local, and it drops the prefixes of the text.findtakes a map from the prefixes of the query to the namespace names, and these prefixes do not need to match the prefixes of the document. A name with no namespace does not match an element in a namespace, sofind("book")returnsNone. On output, ElementTree makes new prefixesns0,ns1and so on, unless the program callsregister_namespace.
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
public class Main {
static final String TEXT = """
<catalog xmlns="urn:example:books" xmlns:m="urn:example:meta">
<book id="b1" m:lang="en">
<title>Tide tables</title>
<price xmlns="urn:example:money" currency="EUR">32.18</price>
</book>
</catalog>""";
static Document parse(boolean aware) throws Exception {
DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
f.setNamespaceAware(aware);
f.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
DocumentBuilder b = f.newDocumentBuilder();
return b.parse(new InputSource(new StringReader(TEXT)));
}
public static void main(String[] args) throws Exception {
Document doc = parse(true);
NodeList all = doc.getElementsByTagNameNS("*", "*");
for (int i = 0; i < all.getLength(); i++) {
Element e = (Element) all.item(i);
System.out.println(e.getNamespaceURI() + " | " + e.getLocalName() + " | " + e.getTagName());
}
Element book = (Element) doc.getElementsByTagNameNS("urn:example:books", "book").item(0);
System.out.println(book.getAttributeNS("urn:example:meta", "lang"));
System.out.println(doc.getElementsByTagNameNS("urn:example:books", "price").getLength());
Document plain = parse(false);
Element first = (Element) plain.getElementsByTagName("book").item(0);
System.out.println(first.getNamespaceURI() + " | " + first.getLocalName() + " | " + first.getAttribute("m:lang"));
}
}
urn:example:books | catalog | catalog
urn:example:books | book | book
urn:example:books | title | title
urn:example:money | price | price
en
0
null | null | en
- Verdict: stdlib. A JAXP
DocumentBuilderFactoryis not namespace-aware by default, so the program callssetNamespaceAware(true). ThengetNamespaceURIandgetLocalNamegive the two parts of the expanded name, andgetElementsByTagNameNSandgetAttributeNSsearch by them. Thepriceelement is in the namespaceurn:example:money, so a search in the books namespace does not find it. With a parser that is not namespace-aware, the namespace and the local name arenull, and the program must use the qualified namem:langas a plain string.
using System.Xml.Linq;
string text = """
<catalog xmlns="urn:example:books" xmlns:m="urn:example:meta">
<book id="b1" m:lang="en">
<title>Tide tables</title>
<price xmlns="urn:example:money" currency="EUR">32.18</price>
</book>
</catalog>
""";
XNamespace b = "urn:example:books";
XNamespace m = "urn:example:meta";
XNamespace money = "urn:example:money";
XElement root = XElement.Parse(text);
XElement book = root.Element(b + "book")!;
Console.WriteLine(root.Name);
Console.WriteLine($"{(string?)book.Attribute(m + "lang")} {(string?)book.Element(b + "title")} {(string?)book.Element(money + "price")}");
Console.WriteLine(root.Element("book") is null);
Console.WriteLine(root.GetPrefixOfNamespace(m));
var item = new XElement(b + "catalog",
new XAttribute(XNamespace.Xmlns + "m", m),
new XElement(b + "book", new XAttribute(m + "lang", "fr"), new XElement(b + "title", "Moon phases")));
Console.WriteLine(item.ToString(SaveOptions.DisableFormatting));
{urn:example:books}catalog
en Tide tables 32.18
True
m
<catalog xmlns:m="urn:example:meta" xmlns="urn:example:books"><book m:lang="fr"><title>Moon phases</title></book></catalog>
- Verdict: stdlib. LINQ to XML gives each name as an
XName, made from anXNamespaceand a local name with the operator+. The cast of anXElementorXAttributetostringgives its text.Element("book")with no namespace finds nothing, because the element is in the books namespace. To choose the prefix of a namespace in the output, the program adds anxmlns:mattribute withXNamespace.Xmlns.
package main
import (
"encoding/xml"
"fmt"
"io"
"strings"
)
const text = `<catalog xmlns="urn:example:books" xmlns:m="urn:example:meta">
<book id="b1" m:lang="en">
<title>Tide tables</title>
<price xmlns="urn:example:money" currency="EUR">32.18</price>
</book>
</catalog>`
type Book struct {
XMLName xml.Name `xml:"urn:example:books book"`
ID string `xml:"id,attr"`
Lang string `xml:"urn:example:meta lang,attr"`
Title string `xml:"urn:example:books title"`
Price string `xml:"urn:example:money price,omitempty"`
}
type Catalog struct {
XMLName xml.Name `xml:"urn:example:books catalog"`
Books []Book `xml:"urn:example:books book"`
}
func main() {
decoder := xml.NewDecoder(strings.NewReader(text))
for {
token, err := decoder.Token()
if err == io.EOF {
break
}
if start, ok := token.(xml.StartElement); ok {
fmt.Printf("%s | %s\n", start.Name.Space, start.Name.Local)
}
}
var catalog Catalog
if err := xml.Unmarshal([]byte(text), &catalog); err != nil {
fmt.Println("error:", err)
return
}
book := catalog.Books[0]
fmt.Println(book.ID, book.Lang, book.Title, book.Price)
wrong := strings.Replace(text, "urn:example:books", "urn:example:other", 1)
err := xml.Unmarshal([]byte(wrong), &catalog)
fmt.Println("error:", err)
out, _ := xml.Marshal(Book{ID: "b2", Lang: "fr", Title: "Moon phases"})
fmt.Println(string(out))
}
urn:example:books | catalog
urn:example:books | book
urn:example:books | title
urn:example:money | price
b1 en Tide tables 32.18
error: expected element <catalog> in name space urn:example:books but have urn:example:other
<book xmlns="urn:example:books" id="b2" xmlns:_="urn:example:meta" _:lang="fr"><title xmlns="urn:example:books">Moon phases</title></book>
- Verdict: stdlib.
encoding/xmlgives each name as anxml.Namewith the fieldsSpace(the namespace name) andLocal. A struct tag of the formxml:"namespace local"matches only the elements in that namespace, andUnmarshalreturns an error when the root is in another namespace.Marshalwrites the namespaces in its own way: it puts anxmlnsattribute on each element and makes a prefix such as_for an attribute in a namespace. The output has the correct expanded names, but it is not the text that a person writes.
Variations and related ideas
- XPath and XSLT. An XPath expression uses prefixes too, but the prefixes of the expression are bound by the program, not by the document. A query for
/catalog/bookfinds nothing in a document with a default namespace. The query must use a prefix bound to the namespace, such as/b:catalog/b:book. - Namespaces of schemas. A schema in XML Schema describes the elements of one target namespace. The namespace URI is the key that links a document to its schema.
- JSON-LD and RDF. The
@contextof JSON-LD and the prefixes of Turtle use the same idea: a short prefix stands for a long IRI. - Namespaces in programming languages. A package or a module name in a programming language is a namespace for the names of the code. An XML namespace does the same for the names of the markup.
Pitfalls
- Searching with the local name only. In a document with a default namespace, every unprefixed element is in that namespace. A search for
bookwith no namespace finds nothing. This is a common bug. The fix is to search with the expanded name. - Depending on the prefix. The prefix is not part of the name. Another writer can use
x:item,itemwith a default namespace, orns0:itemfor the same element. A program that compares the prefix or the qualified namem:langas a string breaks when the prefix changes. - Unprefixed attributes are in no namespace. A program that looks for the attribute
{urn:example:books}idfinds nothing, becauseidhas no prefix. - Prefixes in the output. Some writers do not keep the prefixes of the input. ElementTree writes
ns0andns1unless the program callsregister_namespace, and that registry "is global".3 Go writes anxmlnsattribute on each element and invents prefixes for attributes. The output is correct but hard to read. When people read the output, set the prefixes. - Prefixes inside values. Some vocabularies, such as XML Schema and XSLT, put qualified names inside attribute values, for example
type="xs:string". A writer that changes the prefixes does not change these values, and the document breaks. Keep the original prefixes when you edit such a document. - Case and spelling of the URI. The comparison is a plain string comparison.1 A trailing slash, a different case or a different scheme makes a different namespace.
- The namespace URI is not a link. A program must not fetch the URI to read the document. The URI need not point to anything.1
Cost
Namespaces add a small cost to the parse: the parser keeps a stack of the bindings in scope and looks up each prefix. A tree keeps a namespace name with each element. The larger cost is for people: the expanded names make queries and programs longer.
History
The first edition of Namespaces in XML came out in 1999. The XML 1.0 specification lists it in its references as "Namespaces in XML", by Tim Bray, Dave Hollander and Andrew Layman, World Wide Web Consortium, 1999.2 The third edition of 8 December 2009 "incorporates all known errata as of the publication date" and supersedes the edition of 16 August 2006.1
References
- W3C, Namespaces in XML 1.0 (Third Edition), W3C Recommendation, 8 December 2009, 1 Motivation and Summary; 2.1 Basic Concepts; 2.2 Use of URIs as Namespace Names; 2.3 Comparing URI References; 3 Declaring Namespaces; 6.1 Namespace Scoping; 6.2 Namespace Defaulting; 6.3 Uniqueness of Attributes
- W3C, Extensible Markup Language (XML) 1.0 (Fifth Edition), W3C Recommendation, 26 November 2008, 2.3 Common Syntactic Constructs (the note on the colon)
- The Python Standard Library, xml.etree.ElementTree, Python 3.14, Parsing XML with Namespaces; register_namespace
- Go standard library, package encoding/xml, type Name; func Marshal; func Unmarshal
- Java SE 25 API, javax.xml.parsers.DocumentBuilderFactory, setNamespaceAware
- .NET documentation, Namespaces overview (LINQ to XML), the whole article
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag RNZSX1 Edit this page History Report an error Markdown