XML Namespaces: Prefixes, Default Namespaces and Namespace-Aware Parsing
How XML namespaces keep element names apart: namespace URIs, xmlns prefixes and default namespaces, scoping and attributes, namespace-aware DOM parsing with newNSInstance, getNamespaceURI and getLocalName, getElementsByTagNameNS, and XPath with a NamespaceContext.
kvi5hnuCode Sprout team member8 min readOn this page
As soon as documents combine vocabularies, names collide. An XHTML page with embedded SVG has two different title elements. An order format and a product catalog may both define item. Java avoids class-name clashes with packages. XML uses namespaces.
Namespace names are URIs
A namespace is identified by a URI, for example:
http://www.w3.org/2001/XMLSchema
urn:example:shop
uuid:1c759aed-b748-475c-ab68-10679700c4f2
HTTP URLs are the most common choice, because domain ownership makes them unique, the same idea as reversed domain names in Java package names. But a namespace URI is only an identifier. Parsers never fetch anything from it, and nothing needs to exist there. By convention, the W3C and others put a human-readable description at the address. The comparison is purely by characters: http://example.com/ns and http://example.com/ns/ are different namespaces, as are URIs that differ only in case.
Declaring namespaces
Writing full URIs in every tag would be unbearable, so XML binds them to shorter forms with special xmlns attributes.
A default namespace applies to the element that declares it and all its descendant elements that have no prefix:
<html xmlns="http://www.w3.org/1999/xhtml">
<body>...</body> <!-- also in the XHTML namespace -->
</html>
A child element can declare a different default for its own subtree:
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20">
<circle r="5"/> <!-- in the SVG namespace -->
</svg>
and xmlns="" turns the default off again, putting unprefixed elements back into no namespace.
A prefix binds a short name to a namespace, and then applies only to names written with that prefix:
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="config"/>
</xsd:schema>
A name with a prefix, such as xsd:element, is a qualified name. The part after the colon is its local name. What identifies an element is the pair (namespace URI, local name). The prefix itself has no meaning: <s:item xmlns:s="urn:example:shop"> and <shop:item xmlns:shop="urn:example:shop"> are the same element type. Declarations are scoped to the element where they appear and its descendants, and a nested declaration can rebind a prefix.
Two prefixes are predefined: xml (for attributes such as xml:lang and xml:space) and xmlns itself.
Attributes
Attributes follow a different rule that often surprises people. Unprefixed attributes are in no namespace, even when their element is in a default namespace. In <svg xmlns="http://www.w3.org/2000/svg" width="20">, the attribute width has no namespace. It's simply interpreted relative to its element. Only prefixed attributes, such as xsi:noNamespaceSchemaLocation or xlink:href, belong to a namespace. They're used for "global" attributes that can be attached to elements of any vocabulary.
Namespace-aware parsing
DOM parsers are not namespace-aware by default, for historical reasons. A non-aware parser treats s:order as just a name containing a colon: getNamespaceURI() and getLocalName() return null, and getElementsByTagName matches the literal qualified name. That means code works only as long as documents use the exact prefixes you expect, which no producer guarantees.
Turn awareness on before creating the builder:
var factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
// or, since Java 13:
var factory = DocumentBuilderFactory.newNSInstance();
(SAX parser factories are also non-aware by default and have SAXParserFactory.newNSInstance(). StAX is namespace-aware by default.)
Each element and attribute node then reports three things:
| Method | For <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> |
|---|---|
getNodeName() / getTagName() | xsd:schema (the qualified name) |
getNamespaceURI() | http://www.w3.org/2001/XMLSchema |
getLocalName() | schema |
getPrefix() | xsd |
Code should test the namespace URI and the local name, never the prefix or the qualified name. The namespace-aware variants of the DOM methods take both:
NodeList orders = doc.getElementsByTagNameNS("urn:example:shop", "order");
NodeList anyItem = doc.getElementsByTagNameNS("*", "item"); // any namespace
String id = order.getAttributeNS("urn:example:shop", "id");
String status = order.getAttribute("status"); // a no-namespace attribute
The xmlns declarations themselves show up as attributes in the namespace http://www.w3.org/2000/xmlns/ (XMLConstants.XMLNS_ATTRIBUTE_NS_URI). lookupNamespaceURI(prefix), lookupPrefix(uri) and isDefaultNamespace(uri) tell you which declarations are in scope at a node.
Namespaces in XPath
XPath matches names by namespace and local name too. In XPath 1.0, a name without a prefix in an expression always means no namespace, even if the document has a default namespace. So //body finds nothing in an XHTML document. This is the most common XPath surprise.
The fix is to bind prefixes for use in your expressions with a NamespaceContext. The prefixes in your expressions are independent of those in the document:
xpath.setNamespaceContext(new NamespaceContext() {
public String getNamespaceURI(String prefix) {
return switch (prefix) {
case "h" -> "http://www.w3.org/1999/xhtml";
case "shop" -> "urn:example:shop";
default -> XMLConstants.NULL_NS_URI;
};
}
public String getPrefix(String uri) { ... }
public Iterator<String> getPrefixes(String uri) { ... }
});
xpath.evaluate("//h:body//shop:item", doc);
The JDK has no ready-made implementation of NamespaceContext, so most projects write a small one backed by a map, as the demo does. Only getNamespaceURI is actually used for evaluating expressions. Another approach reuses the document's own declarations through node.lookupNamespaceURI(prefix), and maps a made-up prefix such as _ to the default namespace. That only works if the document declares everything on the root.
Without a context, you can fall back to name tests on functions: //*[local-name()='item' and namespace-uri()='urn:example:shop']. It works, but it's verbose. XPath 2.0's wildcard *:item isn't available in the JDK's XPath 1.0.
The program
The demo parses an XHTML page that contains elements from a "shop" vocabulary, written with two different prefixes, an embedded SVG drawing with its own default namespace, and a paragraph that opts out of any namespace. It parses the page once without and once with namespace awareness, prints the namespace, local name and prefix of every element and attribute, searches by namespace, and runs XPath queries with and without a namespace context.
import java.io.*;
import java.util.*;
import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;
import javax.xml.parsers.*;
import javax.xml.xpath.*;
import org.w3c.dom.*;
import org.xml.sax.InputSource;
public class Solution {
static final String XHTML = "http://www.w3.org/1999/xhtml";
static final String SVG = "http://www.w3.org/2000/svg";
static final String SHOP = "urn:example:shop";
static final String PAGE = """
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:s="urn:example:shop">
<body>
<s:order s:id="17" status="open">
<s:item>Teapot</s:item>
<item>not a shop item</item>
</s:order>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20">
<circle r="5"/>
</svg>
<shop:order xmlns:shop="urn:example:shop" shop:id="18">
<shop:item>Kettle</shop:item>
</shop:order>
<p xmlns="">no namespace here</p>
</body>
</html>""";
static Document parse(DocumentBuilderFactory factory) throws Exception {
return factory.newDocumentBuilder().parse(new InputSource(new StringReader(PAGE)));
}
static void describe(Node n, String indent) {
if (n instanceof Element e) {
System.out.printf("%s%-10s ns=%-29s local=%-7s prefix=%s%n", indent, e.getTagName(),
e.getNamespaceURI(), e.getLocalName(), e.getPrefix());
NamedNodeMap attrs = e.getAttributes();
for (int i = 0; i < attrs.getLength(); i++) {
var a = (Attr) attrs.item(i);
System.out.printf("%s @%-11s ns=%s%n", indent, a.getName(), a.getNamespaceURI());
}
for (Node c = e.getFirstChild(); c != null; c = c.getNextSibling()) describe(c, indent + " ");
}
}
/** Maps prefixes for use in XPath expressions; they need not match the document's prefixes. */
record Prefixes(Map<String, String> map) implements NamespaceContext {
public String getNamespaceURI(String prefix) {
return map.getOrDefault(prefix, XMLConstants.NULL_NS_URI);
}
public String getPrefix(String uri) {
return map.entrySet().stream().filter(e -> e.getValue().equals(uri)).map(Map.Entry::getKey).findFirst().orElse(null);
}
public Iterator<String> getPrefixes(String uri) {
return map.entrySet().stream().filter(e -> e.getValue().equals(uri)).map(Map.Entry::getKey).iterator();
}
}
public static void main(String[] args) throws Exception {
System.out.println("--- without namespace awareness (the DOM default) ---");
Document plain = parse(DocumentBuilderFactory.newInstance());
Element order = (Element) plain.getElementsByTagName("s:order").item(0);
System.out.println("tag " + order.getTagName() + ", namespace " + order.getNamespaceURI()
+ ", local name " + order.getLocalName());
System.out.println("getElementsByTagName(\"order\"): " + plain.getElementsByTagName("order").getLength()
+ ", (\"s:order\"): " + plain.getElementsByTagName("s:order").getLength());
System.out.println("--- namespace-aware ---");
Document doc = parse(DocumentBuilderFactory.newNSInstance());
describe(doc.getDocumentElement(), "");
System.out.println("--- searching by namespace and local name ---");
System.out.println("shop orders: " + doc.getElementsByTagNameNS(SHOP, "order").getLength());
NodeList items = doc.getElementsByTagNameNS(SHOP, "item");
for (int i = 0; i < items.getLength(); i++)
System.out.println(" shop item: " + items.item(i).getTextContent() + " (written as " + items.item(i).getNodeName() + ")");
System.out.println("all <item> in any namespace: " + doc.getElementsByTagNameNS("*", "item").getLength());
Element first = (Element) doc.getElementsByTagNameNS(SHOP, "order").item(0);
System.out.println("getAttributeNS(SHOP, \"id\")=" + first.getAttributeNS(SHOP, "id")
+ ", getAttribute(\"status\")=" + first.getAttribute("status")
+ ", getAttributeNS(SHOP, \"status\")=\"" + first.getAttributeNS(SHOP, "status") + "\"");
System.out.println("lookupNamespaceURI(\"s\")=" + first.lookupNamespaceURI("s")
+ ", lookupPrefix(SHOP)=" + first.lookupPrefix(SHOP)
+ ", isDefaultNamespace(XHTML)=" + first.isDefaultNamespace(XHTML));
System.out.println("--- XPath ---");
XPath plainPath = XPathFactory.newInstance().newXPath();
System.out.println("//body without a context: " + plainPath.evaluateExpression("count(//body)", doc, Integer.class));
System.out.println("by local-name(): " + plainPath.evaluateExpression(
"count(//*[local-name()='item' and namespace-uri()='" + SHOP + "'])", doc, Integer.class));
XPath xpath = XPathFactory.newInstance().newXPath();
xpath.setNamespaceContext(new Prefixes(Map.of("h", XHTML, "shop", SHOP, "g", SVG)));
System.out.println("//h:body: " + xpath.evaluateExpression("count(//h:body)", doc, Integer.class));
System.out.println("//shop:order/shop:item:");
for (Node n : xpath.evaluateExpression("//shop:order/shop:item", doc, XPathNodes.class))
System.out.println(" " + n.getTextContent());
System.out.println("second order's shop:id: " + xpath.evaluate("(//shop:order)[2]/@shop:id", doc));
System.out.println("circle radius: " + xpath.evaluate("//g:svg/g:circle/@r", doc));
System.out.println("unprefixed <item> in XHTML: " + xpath.evaluate("//shop:order/h:item", doc));
System.out.println("no-namespace <p>: " + xpath.evaluate("//h:body/p", doc));
}
}
--- without namespace awareness (the DOM default) ---
tag s:order, namespace null, local name null
getElementsByTagName("order"): 0, ("s:order"): 1
--- namespace-aware ---
html ns=http://www.w3.org/1999/xhtml local=html prefix=null
@xmlns ns=http://www.w3.org/2000/xmlns/
@xmlns:s ns=http://www.w3.org/2000/xmlns/
body ns=http://www.w3.org/1999/xhtml local=body prefix=null
s:order ns=urn:example:shop local=order prefix=s
@s:id ns=urn:example:shop
@status ns=null
s:item ns=urn:example:shop local=item prefix=s
item ns=http://www.w3.org/1999/xhtml local=item prefix=null
svg ns=http://www.w3.org/2000/svg local=svg prefix=null
@height ns=null
@width ns=null
@xmlns ns=http://www.w3.org/2000/xmlns/
circle ns=http://www.w3.org/2000/svg local=circle prefix=null
@r ns=null
shop:order ns=urn:example:shop local=order prefix=shop
@shop:id ns=urn:example:shop
@xmlns:shop ns=http://www.w3.org/2000/xmlns/
shop:item ns=urn:example:shop local=item prefix=shop
p ns=null local=p prefix=null
@xmlns ns=http://www.w3.org/2000/xmlns/
--- searching by namespace and local name ---
shop orders: 2
shop item: Teapot (written as s:item)
shop item: Kettle (written as shop:item)
all <item> in any namespace: 3
getAttributeNS(SHOP, "id")=17, getAttribute("status")=open, getAttributeNS(SHOP, "status")=""
lookupNamespaceURI("s")=urn:example:shop, lookupPrefix(SHOP)=s, isDefaultNamespace(XHTML)=true
--- XPath ---
//body without a context: 0
by local-name(): 2
//h:body: 1
//shop:order/shop:item:
Teapot
Kettle
second order's shop:id: 18
circle radius: 5
unprefixed <item> in XHTML: not a shop item
no-namespace <p>: no namespace here
Points to check in the output:
- Without awareness, the namespace and local name are null, and only the literal
s:orderis found. - Both
s:itemandshop:itemare found as the same kind of element. status,width,heightandrhave no namespace, although their elements do.//bodymatches nothing, while//h:bodywith a context matches.- The unprefixed
<item>inside the shop order is in the XHTML namespace, inherited from the default declaration onhtml.
Common questions
Do I need to own the domain used in a namespace URI?
You should use one you control, so that nobody else picks the same URI by accident. Because nothing is ever fetched, a URN such as urn:example:shop or a URL that doesn't resolve works just as well technically.
Should I change the namespace URI when my format gets a new version?
Only for incompatible changes. A new namespace makes every element a different name, so old software sees nothing it recognizes. Many formats keep the namespace and add a version attribute instead.
How do I make the output use a specific prefix?
With DOM, create elements with createElementNS(uri, "p:name"). With StAX, call setPrefix or writeNamespace. Serializers write the prefix you chose, adding declarations where needed. Readers must not depend on it.
Why does getAttributeNS(null, "width") work but getAttributeNS(svgNs, "width") doesn't?
Unprefixed attributes are in no namespace, even on a namespaced element. Pass null (or "") as the namespace for them.
Does getElementsByTagNameNS accept wildcards?
Yes. "*" as the namespace matches any namespace, and "*" as the local name matches any element. getElementsByTagNameNS("*", "item") finds item elements regardless of namespace.
API reference
| API | Purpose |
|---|---|
DocumentBuilderFactory.newNSInstance() / setNamespaceAware(true) | namespace-aware DOM parsing (Java 13 / 1.4) |
SAXParserFactory.newNSInstance() | namespace-aware SAX parsing (Java 13) |
Node.getNamespaceURI(), getLocalName(), getPrefix() | namespace parts of a name (null without awareness) |
Document/Element.getElementsByTagNameNS(uri, local) | search by namespace; "*" is a wildcard for either |
Element.getAttributeNS(uri, local), hasAttributeNS, setAttributeNS | namespaced attribute access |
Node.lookupNamespaceURI(prefix), lookupPrefix(uri), isDefaultNamespace(uri) | declarations in scope |
XPath.setNamespaceContext(context) | prefixes for XPath expressions |
NamespaceContext.getNamespaceURI(prefix) | map a prefix to a URI |
XMLConstants.NULL_NS_URI, XML_NS_URI, XMLNS_ATTRIBUTE_NS_URI | the empty, xml and xmlns namespace URIs |
Summary
- A namespace is a URI used as an identifier. Nothing is ever fetched from it, and comparison is character by character.
xmlns="uri"sets the default namespace for unprefixed elements in a subtree, andxmlns:p="uri"binds a prefix. Elements are identified by namespace URI plus local name, never by prefix.- Unprefixed attributes are in no namespace.
- DOM and SAX parsers are non-aware by default. Use
newNSInstance()orsetNamespaceAware(true), then work withgetNamespaceURI,getLocalNameand the...NSmethods. - In XPath 1.0, unprefixed names mean no namespace. Bind prefixes with a
NamespaceContextto query namespaced documents.
Practice Questions
Are \<a:x xmlns:a="urn:one"/\> and \<b:x xmlns:b="urn:one"/\> the same element type? What about \<x xmlns="urn:one"/\>?
All three are the same element type: namespace urn:one, local name x. Prefixes and default declarations are only notations for binding the namespace URI.
In \<item xmlns="urn:shop" price="5"/\>, what namespace does price belong to?
None. Unprefixed attributes are never in a namespace, regardless of default namespace declarations. Only a prefixed attribute, such as s:price with s bound to urn:shop, would be in that namespace.
Your code calls element.getLocalName() and gets null. Why?
The document was parsed without namespace awareness, which is the DOM default. Create the builder from DocumentBuilderFactory.newNSInstance() or call setNamespaceAware(true) on the factory first.
Why does xpath.evaluate("//title", xhtmlDoc) return an empty string for a valid XHTML page?
XHTML elements are in the default namespace http://www.w3.org/1999/xhtml, but an unprefixed name in an XPath 1.0 expression means "no namespace". Bind a prefix such as h to the XHTML namespace in a NamespaceContext and write //h:title, or use //*[local-name()='title'].
Why is code that checks element.getTagName().equals("xsd:element") fragile?
It depends on the prefix that the author of the document happened to choose. Another document might use xs:element, or a default namespace, and be equally correct. Check getNamespaceURI() against XMLConstants.W3C_XML_SCHEMA_NS_URI and getLocalName() against "element" instead.
Previous: Querying XML with XPath: Expressions and the XPath API
Related reading
- Querying XML with XPath: Expressions and the XPath API
- Validating XML with XML Schema: Types, Sequences and a Practical Example
- Validating XML with Document Type Definitions (DTDs)
- Parsing XML with DOM: DocumentBuilder, Nodes and Secure Parsing
- Introducing XML: Document Structure, Elements and Attributes

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.