XML Namespaces — xmlns, Default Namespaces, Prefix Binding, Scope Rules, XPath with Namespaces
XML namespaces prevent element name conflicts when combining XML documents from different sources. This guide covers namespace declaration syntax, scoping rules, prefix binding, and namespace-aware XPath queries.
What You’ll Learn
You’ll declare namespaces with xmlns and xmlns:prefix, understand namespace scoping and inheritance, resolve namespace conflicts, write namespace-aware XPath expressions, and handle namespaces correctly in DOM and SAX parsing.
Learning Path
flowchart LR
A[SAX Parsing] --> B[XML Namespaces<br/>You are here]
B --> C[DTD Validation]
C --> D[XQuery Basics]
style B fill:#f90,color:#fff
Namespace Declaration
Namespaces are declared using the xmlns attribute:
<!-- Default namespace (no prefix) -->
<book xmlns="http://dodatech.com/ns/books">
<title>XML Namespaces Guide</title>
<author>Alice Smith</author>
</book>
<!-- Prefixed namespace -->
<bk:book xmlns:bk="http://dodatech.com/ns/books">
<bk:title>XML Namespaces Guide</bk:title>
<bk:author>Alice Smith</bk:author>
</bk:book>Multiple Namespaces
<order xmlns="http://dodatech.com/ns/orders"
xmlns:addr="http://dodatech.com/ns/address"
xmlns:pay="http://dodatech.com/ns/payment">
<order-id>12345</order-id>
<addr:address>
<addr:street>123 Main St</addr:street>
<addr:city>New York</addr:city>
</addr:address>
<pay:payment>
<pay:method>credit-card</pay:method>
<pay:amount>99.95</pay:amount>
</pay:payment>
</order>Scope and Inheritance
Namespace declarations apply to the declaring element and all its descendants:
<root xmlns:ns="http://dodatech.com/ns">
<ns:child>
<!-- Inherits ns prefix from root -->
<ns:grandchild>Text</ns:grandchild>
</ns:child>
</root>Overriding Namespaces
<out:outer xmlns:out="http://dodatech.com/ns/outer">
<out:child>
<!-- Inner namespace overrides outer for this subtree -->
<out:grandchild xmlns:out="http://dodatech.com/ns/inner">
This element uses inner namespace
</out:grandchild>
<out:other-child>
This element uses outer namespace again
</out:other-child>
</out:child>
</out:outer>Namespace in XPath
XPath queries must account for namespaces:
<bk:bookstore xmlns:bk="http://dodatech.com/ns/books">
<bk:book bk:category="fiction">
<bk:title>XML Namespaces</bk:title>
<bk:author>Alice Smith</bk:author>
</bk:book>
</bk:bookstore>Java XPath with Namespace
import javax.xml.parsers.*;
import javax.xml.xpath.*;
import org.w3c.dom.*;
public class NamespaceXPathExample {
public static void main(String[] args) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true); // CRITICAL for namespaces
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse("books.xml");
// Create XPath with namespace context
XPathFactory xpf = XPathFactory.newInstance();
XPath xpath = xpf.newXPath();
// Register namespace prefix for XPath
xpath.setNamespaceContext(new NamespaceContext() {
@Override
public String getNamespaceURI(String prefix) {
return switch (prefix) {
case "bk" -> "http://dodatech.com/ns/books";
case "xml" -> "http://www.w3.org/XML/1998/namespace";
default -> XMLConstants.NULL_NS_URI;
};
}
@Override
public String getPrefix(String uri) {
throw new UnsupportedOperationException();
}
@Override
public Iterator<String> getPrefixes(String uri) {
throw new UnsupportedOperationException();
}
});
// Query using namespace prefix
String expr = "/bk:bookstore/bk:book/bk:title";
NodeList titles = (NodeList) xpath.evaluate(
expr, doc, XPathConstants.NODESET);
for (int i = 0; i < titles.getLength(); i++) {
System.out.println(
"Title: " + titles.item(i).getTextContent());
}
// Query with attribute namespace
String attrExpr =
"//bk:book[@bk:category='fiction']/bk:title";
NodeList fictionTitles = (NodeList) xpath.evaluate(
attrExpr, doc, XPathConstants.NODESET);
System.out.println("Fiction titles: "
+ fictionTitles.getLength());
}
}Python XPath with Namespace
from lxml import etree
# Parse with namespace awareness
tree = etree.parse('books.xml')
root = tree.getroot()
# Register namespace
ns = {'bk': 'http://dodatech.com/ns/books'}
# Query with namespace
titles = tree.xpath('//bk:title', namespaces=ns)
for title in titles:
print(f"Title: {title.text}")
# Query with attribute
fiction = tree.xpath(
"//bk:book[@bk:category='fiction']/bk:title",
namespaces=ns
)
print(f"Fiction titles: {len(fiction)}")Common Namespace Mistakes
1. Not Setting NamespaceAware
Without factory.setNamespaceAware(true) in Java DOM, namespaces are treated as regular attributes. Elements ns:element are parsed as element name ns:element (literal colon), not element in namespace ns.
2. Confusing Default and Prefixed Namespaces
Default namespace (xmlns="...") applies to elements without prefixes — but attributes without prefixes are NOT in the namespace. Only explicitly prefixed attributes (ns:attr="value") are namespace-qualified.
3. XPath Without Namespace Context
XPath expressions without namespace context never match namespace-qualified elements. Always register namespace prefixes matching the document’s declarations.
4. Namespace URI Mismatch
http://dodatech.com/ns/books ≠ http://dodatech.com/ns/books/ (trailing slash). Namespace URIs must match exactly — they’re compared as strings, not resolved.
5. Ignoring xmlns in Generated XML
When generating XML with namespaces, always include the xmlns declaration. Consumers may fail if the namespace is expected but missing.
Practice Questions
1. What is the purpose of xmlns?
xmlns declares an XML namespace. A namespace is a URI that uniquely identifies a set of element and attribute names, preventing conflicts when combining XML from different sources.
2. How does namespace inheritance work? A namespace declared on a parent element applies to all descendant elements unless overridden. Descendants can declare their own namespace, which applies from that point inward.
3. What’s the difference between default and prefixed namespaces?
Default namespace (xmlns="uri") applies to elements without prefixes. Prefixed namespace (xmlns:bk="uri") is referenced using the prefix (<bk:element>). Attributes without prefixes are never in a namespace.
4. Why don’t XPath queries match namespace-qualified elements by default? XPath considers namespace as part of the element’s identity. Without registering the namespace URI with a prefix in the XPath evaluation context, the query can’t match namespace-qualified elements.
5. Challenge: Given two XML documents using different namespace URIs for “book” elements, design an XSLT that merges them into a single output using a common namespace.
Answer: In XSLT, declare both source namespaces and the target namespace. Use <xsl:element name="bk:book" namespace="http://common/ns"> to create output in the target namespace, mapping source elements appropriately.
Mini Project: Namespace Inspector
import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.util.*;
public class NamespaceInspector {
public static void inspectNamespaces(Node node, Set<String> uris) {
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
// Check for namespace on this element
String ns = element.getNamespaceURI();
if (ns != null) {
uris.add(ns);
}
// Check for namespace declarations
NamedNodeMap attrs = element.getAttributes();
if (attrs != null) {
for (int i = 0; i < attrs.getLength(); i++) {
Attr attr = (Attr) attrs.item(i);
if (attr.getName().startsWith("xmlns")) {
String prefix = attr.getName().equals("xmlns")
? "(default)"
: attr.getName().substring(6);
System.out.printf(" xmlns:%s = %s%n",
prefix, attr.getValue());
}
}
}
}
// Recurse
NodeList children = node.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
inspectNamespaces(children.item(i), uris);
}
}
public static void main(String[] args) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse("books.xml");
System.out.println("=== Namespace Analysis ===");
Set<String> namespaces = new TreeSet<>();
inspectNamespaces(doc.getDocumentElement(), namespaces);
System.out.println("\nNamespaces used:");
for (String ns : namespaces) {
System.out.println(" " + ns);
}
}
}FAQ
What’s Next
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. Updated 2026-06-20.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro