Parsing XML with DOM: DocumentBuilder, Nodes and Secure Parsing
Read XML into a DOM tree with DocumentBuilderFactory and DocumentBuilder, walk Node, Element, Text and Attr objects, cope with whitespace text nodes, search with getElementsByTagName, and parse untrusted XML safely against XXE and entity-expansion attacks.
kvi5hnuCode Sprout team member11 min readOn this page
To use the data in an XML document, a program first has to parse it: read the characters, check that they're well-formed, and turn them into something the program can navigate. The JDK offers two families of parsers:
- Tree parsers read the whole document into memory as a tree of objects. The standard is the W3C Document Object Model (DOM).
- Streaming parsers report the document piece by piece as it's read, without building a tree. SAX and StAX, covered in article 45, work this way.
A DOM tree is the easiest to work with, so we start there. Use a streaming parser for very large documents, or when you need only a few values and don't care about their context.
Getting a DOM parser
The DOM interfaces (Document, Element, Node and so on) are defined by the W3C in the package org.w3c.dom. JAXP lets any vendor's implementation be plugged in. The JDK ships its own, which is derived from Apache Xerces. You never name the implementation class. Instead, you go through a factory:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(file); // a File
Document doc = builder.parse(uriString); // a URI such as "https://..." or "file:..."
Document doc = builder.parse(inputStream); // any InputStream
Document doc = builder.parse(new InputSource(new StringReader(xml))); // text in a String
Configure the factory (see below) before creating builders. A DocumentBuilder isn't thread-safe, but it can be reused for many documents in one thread, and reset() restores its original configuration.
By default, parse errors go to an error handler that prints [Fatal Error] ... to standard error and throws a SAXParseException. Install your own ErrorHandler with builder.setErrorHandler to control the output. SAXParseException reports getLineNumber() and getColumnNumber().
The tree
A Document represents the whole document. Everything in it is a Node, and there's a subinterface for each kind of node:
| Interface | getNodeType() | getNodeName() | getNodeValue() |
|---|---|---|---|
Document | DOCUMENT_NODE | #document | null |
Element | ELEMENT_NODE | tag name | null |
Attr | ATTRIBUTE_NODE | attribute name | attribute value |
Text | TEXT_NODE | #text | the text |
CDATASection (a Text) | CDATA_SECTION_NODE | #cdata-section | the text |
Comment | COMMENT_NODE | #comment | the comment |
ProcessingInstruction | PROCESSING_INSTRUCTION_NODE | target | data |
DocumentType | DOCUMENT_TYPE_NODE | root name from DOCTYPE | null |
EntityReference | ENTITY_REFERENCE_NODE | entity name | null |
Text, Comment and CDATASection share the superinterface CharacterData, whose getData() returns the characters. With pattern matching for instanceof or switch, dispatching on node kinds is concise: if (child instanceof Element e) ....
Start at the root with doc.getDocumentElement(). getTagName() returns an element's name.
Whitespace is text
Take this document:
<font>
<!-- the face -->
<name>Helvetica</name>
<size unit="pt">
36
</size>
</font>
You might expect font to have two children. The parser reports seven: the comment, the two elements, and four text nodes holding nothing but line breaks and spaces. The parser can't know that this whitespace is just indentation. Only a DTD or schema that declares font as element-only content can tell it (article 41). Until then, your code must skip whitespace text, typically by looking only at Element children:
NodeList children = root.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
if (children.item(i) instanceof Element child) {
...
}
}
NodeList predates the collections framework. It has only getLength() and item(i), and it isn't Iterable. A small helper that collects the child elements into a List<Element> makes the rest of the code nicer, as in the demo. Alternatively, follow the sibling links:
for (Node n = element.getFirstChild(); n != null; n = n.getNextSibling()) ...
getLastChild, getPreviousSibling and getParentNode complete the navigation methods.
Text and attributes
The text of <name>Helvetica</name> lives in a Text child of the element. You can fetch it with ((Text) element.getFirstChild()).getData(), but element.getTextContent() is simpler and safer. It concatenates all text in the element's subtree, and it returns "" instead of failing when the element is empty. Call strip() on the result, since a value written as
<size>
36
</size>
includes the surrounding line breaks and indentation.
For attributes, element.getAttribute("unit") returns the value, or the empty string when the attribute is missing. Use hasAttribute to tell "missing" apart from "empty". To enumerate all attributes, getAttributes() returns a NamedNodeMap of Attr nodes, iterated with getLength() and item(i) and read with getNodeName() and getNodeValue(). The order of attributes in this map isn't the order in the file, since XML attribute order carries no meaning.
Searching
getElementsByTagName(name), available on both Document and Element, returns all descendant elements with the given name in document order, at any depth. Pass "*" to get all elements. That's often enough for simple documents. For anything more selective, use XPath (article 43).
Useful factory settings
| Setting | Effect |
|---|---|
setIgnoringComments(true) | drop comment nodes |
setCoalescing(true) | turn CDATA sections into text and merge them with adjacent text |
setIgnoringElementContentWhitespace(true) | drop whitespace in element-only content, but only when validating against a DTD |
setNamespaceAware(true) | process namespaces (article 44); off by default for DOM |
setValidating(true) | validate against the document's DTD (article 41) |
setSchema(schema) | validate against an XML Schema (article 42) |
setExpandEntityReferences(false) | keep EntityReference nodes instead of their replacement text |
setXIncludeAware(true) | process XInclude directives |
After you build or modify a tree yourself, node.normalize() merges adjacent text nodes and removes empty ones, giving the same shape a parser would produce.
Parsing untrusted XML safely
XML parsers process DTDs, and a DTD can declare entities, including external ones that refer to a file or URL. That makes a plain parser dangerous when the XML comes from an untrusted source:
- XXE (XML External Entity) attacks. A document such as
makes the parser read a local file and paste it into the document, from where the application may echo it back. Withxml
<!DOCTYPE r [<!ENTITY x SYSTEM "file:///etc/passwd">]> <r>&x;</r>http:URLs, the server can be made to send requests inside your network (server-side request forgery). - Entity expansion ("billion laughs"). Nested internal entities, each referring ten times to the previous one, expand to gigabytes of text from a few hundred bytes of input.
The demo shows that the JDK's default DocumentBuilderFactory still resolves an external entity pointing to a local file. Defenses, from strongest to most targeted:
- Disallow DTDs entirely if your documents don't need them (most data formats don't):
Since JDK 22, the JDK-specific propertyjava
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);jdk.xml.dtd.supportdoes the same with the valuesallow,ignoreordeny, either throughfactory.setAttributeor as a system property. - Forbid external access while still allowing internal DTD subsets:
The value is a comma-separated list of allowed protocols, such asjava
factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");"file"or"https", and the empty string allows none. Explicitly callingfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true)has the same effect in the JDK: it sets both properties to the empty string (we checked this on JDK 25). The feature is already on by default for its processing limits, but external access is only cut off when you set it yourself. - Rely on processing limits. The JDK caps entity expansions, entity sizes, element depth, attribute counts and more. The demo's small "laughs" document hits the limit right away.
The same concerns apply to every JAXP factory: SAXParserFactory, XMLInputFactory (StAX), SchemaFactory, TransformerFactory and XPathFactory. The OWASP "XML External Entity Prevention Cheat Sheet" lists the settings for each.
The program
The demo prints the complete tree of the font document, including whitespace text and the comment, and then extracts the values while skipping the noise. It searches a configuration document with getElementsByTagName, compares factory options, and ends with the security part. The default factory reads a "secret" temporary file through an external entity, the three defenses stop it, and the entity-expansion limit rejects a small "billion laughs" document.
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import javax.xml.XMLConstants;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
public class Solution {
static final String FONT = """
<?xml version="1.0"?>
<font>
<!-- the face -->
<name>Helvetica</name>
<size unit="pt">
36
</size>
</font>""";
static final String CONFIG = """
<config>
<entry id="title"><font><name>Helvetica</name><size unit="pt">36</size></font></entry>
<entry id="body"><font><name>Times Roman</name><size unit="pt">12</size></font></entry>
<entry id="background"><color><red>0</red><green>50</green><blue>100</blue></color></entry>
</config>""";
static final ErrorHandler QUIET = new ErrorHandler() {
public void warning(SAXParseException e) { }
public void error(SAXParseException e) { }
public void fatalError(SAXParseException e) throws SAXException { throw e; }
};
static Document parse(DocumentBuilderFactory factory, String xml) throws Exception {
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setErrorHandler(QUIET);
return builder.parse(new InputSource(new StringReader(xml)));
}
static String esc(String s) {
return s.replace("\n", "\\n").replace("\t", "\\t");
}
/** Print the full tree, one node per line. */
static void dump(Node node, String indent) {
String kind = switch (node.getNodeType()) {
case Node.ELEMENT_NODE -> "Element <" + node.getNodeName() + ">";
case Node.TEXT_NODE -> "Text \"" + esc(node.getNodeValue()) + "\"";
case Node.COMMENT_NODE -> "Comment \"" + esc(node.getNodeValue()) + "\"";
case Node.CDATA_SECTION_NODE -> "CDATA \"" + esc(node.getNodeValue()) + "\"";
case Node.DOCUMENT_NODE -> "Document";
default -> node.getClass().getSimpleName();
};
System.out.println(indent + kind);
NamedNodeMap attrs = node.getAttributes();
if (attrs != null)
for (int i = 0; i < attrs.getLength(); i++)
System.out.println(indent + " @" + attrs.item(i).getNodeName() + "=\"" + attrs.item(i).getNodeValue() + "\"");
for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling())
dump(child, indent + " ");
}
/** NodeList is not Iterable; adapt the child elements to a List. */
static List<Element> childElements(Node parent) {
var result = new ArrayList<Element>();
NodeList children = parent.getChildNodes();
for (int i = 0; i < children.getLength(); i++)
if (children.item(i) instanceof Element e) result.add(e);
return result;
}
public static void main(String[] args) throws Exception {
var factory = DocumentBuilderFactory.newInstance();
System.out.println("--- the raw tree ---");
Document doc = parse(factory, FONT);
dump(doc, "");
Element root = doc.getDocumentElement();
System.out.println("root.getChildNodes().getLength() = " + root.getChildNodes().getLength());
System.out.println("--- reading values ---");
String name = null;
int size = 0;
String unit = null;
for (Element child : childElements(root)) {
String text = child.getTextContent().strip();
switch (child.getTagName()) {
case "name" -> name = text;
case "size" -> { size = Integer.parseInt(text); unit = child.getAttribute("unit"); }
default -> { }
}
}
System.out.println("name=" + name + ", size=" + size + ", unit=" + unit
+ ", missing attribute=\"" + root.getAttribute("style") + "\", hasAttribute=" + root.hasAttribute("style"));
System.out.println("--- searching the tree ---");
Document config = parse(factory, CONFIG);
NodeList entries = config.getElementsByTagName("entry");
for (int i = 0; i < entries.getLength(); i++) {
var entry = (Element) entries.item(i);
Element value = childElements(entry).get(0);
System.out.println(entry.getAttribute("id") + " -> " + value.getTagName() + " "
+ childElements(value).stream().map(e -> e.getTagName() + "=" + e.getTextContent()).toList());
}
System.out.println("all <name> elements: " + config.getElementsByTagName("name").getLength());
Element blue = (Element) config.getElementsByTagName("blue").item(0);
System.out.println("blue's ancestors: " + ((Element) blue.getParentNode()).getTagName() + " < "
+ ((Element) blue.getParentNode().getParentNode()).getAttribute("id"));
System.out.println("--- factory options ---");
var tidy = DocumentBuilderFactory.newInstance();
tidy.setIgnoringComments(true);
tidy.setCoalescing(true);
Element p = parse(tidy, "<p>a<!-- c --><![CDATA[<b>]]>&z</p>").getDocumentElement();
Element p0 = parse(factory, "<p>a<!-- c --><![CDATA[<b>]]>&z</p>").getDocumentElement();
System.out.println("default: " + p0.getChildNodes().getLength() + " children; tidy: "
+ p.getChildNodes().getLength() + " child \"" + p.getFirstChild().getNodeValue() + "\"");
Element q = parse(factory, "<p>x</p>").getDocumentElement();
q.appendChild(q.getOwnerDocument().createTextNode("y"));
System.out.print("adjacent text nodes: " + q.getChildNodes().getLength());
q.normalize();
System.out.println(", after normalize(): " + q.getChildNodes().getLength());
System.out.println("--- XML external entities (XXE) ---");
Path secret = Files.createTempFile("secret", ".txt");
Files.writeString(secret, "db-password=hunter2", StandardCharsets.UTF_8);
String attack = "<!DOCTYPE r [<!ENTITY x SYSTEM \"" + secret.toUri() + "\">]><r>&x;</r>";
try {
System.out.println("default factory reads: " + parse(factory, attack).getDocumentElement().getTextContent());
var noDoctype = DocumentBuilderFactory.newInstance();
noDoctype.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
try {
parse(noDoctype, attack);
} catch (SAXParseException e) {
System.out.println("disallow-doctype-decl: " + e.getMessage());
}
var noExternal = DocumentBuilderFactory.newInstance();
noExternal.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
noExternal.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
try {
System.out.println("ACCESS_EXTERNAL_DTD=\"\": " + parse(noExternal, attack).getDocumentElement().getTextContent());
} catch (SAXParseException e) {
System.out.println("ACCESS_EXTERNAL_DTD=\"\": " + e.getMessage().replaceAll("secret\\d+", "secret…"));
}
var denyDtd = DocumentBuilderFactory.newInstance();
denyDtd.setAttribute("jdk.xml.dtd.support", "deny");
try {
parse(denyDtd, attack);
} catch (SAXParseException e) {
System.out.println("jdk.xml.dtd.support=deny: " + e.getMessage().replaceAll("\\s+", " "));
}
} finally {
Files.delete(secret);
}
System.out.println("--- entity expansion limits ---");
var bomb = new StringBuilder("<!DOCTYPE r [<!ENTITY a0 \"lol\">");
for (int i = 1; i <= 6; i++)
bomb.append("<!ENTITY a").append(i).append(" \"").append(("&a" + (i - 1) + ";").repeat(10)).append("\">");
bomb.append("]><r>&a6;</r>");
try {
parse(factory, bomb.toString());
System.out.println("expanded");
} catch (SAXParseException e) {
System.out.println("rejected: " + e.getMessage().replaceAll("\\s+", " "));
}
}
}
--- the raw tree ---
Document
Element <font>
Text "\n "
Comment " the face "
Text "\n "
Element <name>
Text "Helvetica"
Text "\n "
Element <size>
@unit="pt"
Text "\n 36\n "
Text "\n"
root.getChildNodes().getLength() = 7
--- reading values ---
name=Helvetica, size=36, unit=pt, missing attribute="", hasAttribute=false
--- searching the tree ---
title -> font [name=Helvetica, size=36]
body -> font [name=Times Roman, size=12]
background -> color [red=0, green=50, blue=100]
all <name> elements: 2
blue's ancestors: color < background
--- factory options ---
default: 4 children; tidy: 1 child "a<b>&z"
adjacent text nodes: 2, after normalize(): 1
--- XML external entities (XXE) ---
default factory reads: db-password=hunter2
disallow-doctype-decl: DOCTYPE is disallowed when the feature "http://apache.org/xml/features/disallow-doctype-decl" set to true.
ACCESS_EXTERNAL_DTD="": External Entity: Failed to read external document 'secret….txt', because 'file' access is not allowed due to restriction set by the accessExternalDTD property.
jdk.xml.dtd.support=deny: JAXP00010008: DOCTYPE is disallowed when the DTD property is set to deny. Refer to: property jdk.xml.dtd.support in java.xml/module-summary.
--- entity expansion limits ---
rejected: JAXP00010001: The parser has encountered more than "2500" entity expansions in this document; this is the limit imposed by "jdk.xml.entityExpansionLimit".
Common questions
How do I parse XML held in a String?
builder.parse(new InputSource(new StringReader(xml))). Avoid converting the string to bytes yourself, which may introduce an encoding mismatch with the XML declaration.
How much memory does a DOM tree need? Typically several times the file size, often 5 to 10 times, because every element, attribute and text node is an object. A 100 MB document can need a gigabyte of heap. For large documents, use SAX or StAX (article 45), or extract only the parts you need.
Are there easier APIs than the W3C DOM? Yes, outside the JDK: JDOM and dom4j offer Java-friendly trees with real collections, and Jackson's XML module or Jakarta XML Binding map XML directly to objects. Inside the JDK, XPath (article 43) is the biggest convenience: it often replaces pages of DOM navigation with one expression.
How do I read an attribute as a number?
Integer.parseInt(element.getAttribute("size")). Check hasAttribute first, because a missing attribute yields "", which throws NumberFormatException. Schema validation (article 42) can guarantee that the value is a valid integer before your code runs.
Why does getTextContent() return text from child elements too?
It returns the concatenated text of the whole subtree. For an element with mixed content, read only its direct Text children if you need the element's own text.
Is DocumentBuilderFactory expensive to create?
newInstance() looks up the implementation, which takes some time, so create and configure a factory once and reuse it. Builders are cheap, but not thread-safe: use one per thread, or a ThreadLocal.
API reference
| API | Purpose |
|---|---|
DocumentBuilderFactory.newInstance() | get the configured DOM factory |
factory.newDocumentBuilder() | create a parser |
factory.setFeature(name, value), setAttribute(name, value) | parser features and properties, including security ones |
builder.parse(File / String uri / InputStream / InputSource) | parse a document |
builder.setErrorHandler(handler), setEntityResolver(resolver) | control errors and external references |
Document.getDocumentElement() | the root element |
Document/Element.getElementsByTagName(name) | all matching descendants |
Element.getTagName(), getAttribute(name), hasAttribute(name) | element name, attribute access |
Node.getChildNodes(), getFirstChild(), getNextSibling(), getParentNode() | navigation |
Node.getNodeType(), getNodeName(), getNodeValue(), getAttributes() | generic node information |
Node.getTextContent() | all text below a node |
CharacterData.getData() | text of a text, CDATA or comment node |
NodeList.getLength(), item(i); NamedNodeMap.getLength(), item(i) | pre-collections lists |
Node.normalize() | merge adjacent text nodes |
XMLConstants.ACCESS_EXTERNAL_DTD, ACCESS_EXTERNAL_SCHEMA | allowed protocols for external resources |
Summary
- Get a parser from
DocumentBuilderFactory, thenparsea file, URI, stream orInputSourceinto aDocument. - The tree consists of
Nodes: elements, text, attributes, comments and more.getDocumentElementis the entry point. - Indentation becomes whitespace text nodes. Skip them by looking only at
Elementchildren, unless a DTD lets the parser drop them. - Read text with
getTextContent().strip(), and attributes withgetAttribute, which returns""when the attribute is missing. getElementsByTagNamefinds descendants anywhere in the tree.- For untrusted XML, disallow DOCTYPE declarations or at least block external access, and keep the JDK's processing limits in place.
Practice Questions
An element \<point\>\<x\>1\</x\>\<y\>2\</y\>\</point\> reports two children, but the same element spread over four indented lines reports five. Why?
In the indented version, the line breaks and spaces between the tags become three text nodes, before x, between x and y, and after y. Without a DTD, the parser can't know that point has element-only content, so it keeps them.
What is the difference between getFirstChild().getNodeValue() and getTextContent() on an element?
getFirstChild().getNodeValue() returns the value of one node. That's only the text if the first child is a text node, it fails with a NullPointerException if the element is empty, and it returns just one chunk if the text is split by a comment or CDATA section. getTextContent() concatenates the text of all descendants and returns "" for an empty element.
How do you tell \<item price=""/\> from \<item/\> using the DOM API?
getAttribute("price") returns "" in both cases. hasAttribute("price") returns true only for the first one.
A web service accepts XML orders and returns validation errors that include the offending text. What attack is it exposed to, and what is the simplest fix?
XXE. An attacker can declare an external entity referring to a server file or internal URL, use it in the order, and read the contents back in the error message. If orders never need a DTD, set the feature http://apache.org/xml/features/disallow-doctype-decl to true (or jdk.xml.dtd.support to deny). Otherwise set ACCESS_EXTERNAL_DTD and ACCESS_EXTERNAL_SCHEMA to the empty string.
After upgrading to JDK 24, a batch job fails with "JAXP00010001: The parser has encountered more than "2500" entity expansions". What happened, and what are the options?
JDK 24 lowered the default XML processing limits, including the entity expansion limit (previously 64,000). If the documents are trusted and legitimately use many entities, raise that specific limit, for example with -Djdk.xml.entityExpansionLimit=..., factory.setAttribute, or a custom configuration file passed with -Djava.xml.config.file. Don't remove the limits for documents that come from untrusted sources.
Previous: Introducing XML: Document Structure, Elements and Attributes
Related reading
- Introducing XML: Document Structure, Elements and Attributes
- Java Regex Split, Replace and Flags: splitWithDelimiters, replaceAll and Pattern Flags
- Java Regex Matching: matches, find, Groups and Named Groups
- Java Regular Expressions: Syntax, Character Classes and Quantifiers
- Java Serialization: readResolve, writeReplace, Versioning and Security

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.