Java DOM Parser: Reading, Writing & Modifying XML

The DOM parser reads a whole XML document into a tree of node objects in memory, which you can query, change and write back. It is the most convenient XML API in the JDK for small and medium documents, and the one where the default settings are unsafe for untrusted input. This page explains the tree model, then runs reading, namespaces, editing and safe parsing, and measures how much memory a DOM tree takes.

Share

Contents

How DOM parsing works

DOM (Document Object Model) is a W3C standard API for XML trees, the same model a web browser uses for HTML. The parser reads the whole document and builds one object per node: the document itself, every element, attribute, piece of text, comment and processing instruction. The tree is then independent of the input, so you can walk it in any order, change it and write it out again. The cost is memory, because every node is a Java object with references to its parent, children and siblings.

Java reaches the parser through JAXP (Java API for XML Processing), part of the JDK since Java 1.4 in the java.xml module. DocumentBuilderFactory.newInstance() looks up an implementation, normally the JDK's built-in copy of Apache Xerces, so code never names a parser class. The DOM interfaces themselves live in org.w3c.dom.

DOM node types
InterfaceNode type constantExample
DocumentDOCUMENT_NODE (9)The root of the tree, above the root element
ElementELEMENT_NODE (1)<book id="b1">
AttrATTRIBUTE_NODE (2)id="b1", reached through the element, not as a child
TextTEXT_NODE (3)Character data, including whitespace between elements
CDATASectionCDATA_SECTION_NODE (4)<![CDATA[a < b]]>
ProcessingInstructionPROCESSING_INSTRUCTION_NODE (7)<?report style="short"?>
CommentCOMMENT_NODE (8)<!-- note -->

All programs use only the JDK and were run on JDK 21.

Reading a document

DocumentBuilderFactory creates a parser, and parse returns a Document, the root of the tree. The program reads a small catalog of two books, each with an attribute in a different language and a price in a different currency, so every value printed comes from a different part of the tree.

Java
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class DomRead {

    static final String XML = """
            <?xml version="1.0" encoding="UTF-8"?>
            <catalog>
              <book id="b1" lang="en">
                <title>Effective Java</title>
                <price currency="USD">45.00</price>
              </book>
              <book id="b2" lang="de">
                <title>Java ist auch eine Insel</title>
                <price currency="EUR">49.90</price>
              </book>
            </catalog>
            """;

    public static void main(String[] args) throws Exception {
        DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
        Document doc = f.newDocumentBuilder().parse(new InputSource(new StringReader(XML)));

        Element root = doc.getDocumentElement();
        System.out.println("root element: " + root.getTagName());

        // getElementsByTagName searches the whole subtree
        NodeList books = doc.getElementsByTagName("book");
        for (int i = 0; i < books.getLength(); i++) {
            Element book = (Element) books.item(i);
            Element price = (Element) book.getElementsByTagName("price").item(0);
            System.out.printf("%s [%s] %s %s %s%n", book.getAttribute("id"),
                    book.getAttribute("lang"),
                    book.getElementsByTagName("title").item(0).getTextContent(),
                    price.getAttribute("currency"), price.getTextContent());
        }

        // getChildNodes includes the whitespace between elements as text nodes
        NodeList children = root.getChildNodes();
        int elements = 0;
        int whitespace = 0;
        for (int i = 0; i < children.getLength(); i++) {
            if (children.item(i).getNodeType() == Node.ELEMENT_NODE) {
                elements++;
            } else if (children.item(i).getNodeType() == Node.TEXT_NODE) {
                whitespace++;
            }
        }
        System.out.println("children of <catalog>: " + children.getLength() + " nodes = "
                + elements + " elements + " + whitespace + " whitespace text nodes");

        // A missing attribute returns "" rather than null
        System.out.println("missing attribute: [" + root.getAttribute("version")
                + "], hasAttribute: " + root.hasAttribute("version"));
    }
}

Output:

Output
root element: catalog
b1 [en] Effective Java USD 45.00
b2 [de] Java ist auch eine Insel EUR 49.90
children of <catalog>: 5 nodes = 2 elements + 3 whitespace text nodes
missing attribute: [], hasAttribute: false
  • getElementsByTagName finds matching elements anywhere below the node it is called on, so book.getElementsByTagName("price") stays inside that one book.
  • getTextContent returns all the text inside an element, including that of nested elements.
  • getChildNodes on <catalog> returns 5 nodes for 2 books: the line breaks and indentation between elements are text nodes too. Code that loops over child nodes must check getNodeType(), a frequent source of ClassCastException.
  • getAttribute returns an empty string, not null, for a missing attribute; use hasAttribute to tell the difference.

Every node in the tree

Elements and text are not the whole story. The note below contains a processing instruction, attributes, a comment and a CDATA section, so a recursive walk can show every node type a typical document produces, and what the factory's options change.

Java
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;

public class NodeTypes {

    static final String XML = """
            <?xml version="1.0"?>
            <?report style="short"?>
            <note id="n1" priority="high">
              <!-- written by hand -->
              <to>Ana</to>
              <body>Use <![CDATA[<b>bold</b> & more]]> carefully</body>
            </note>""";

    static final String[] NAMES = {"", "ELEMENT", "ATTRIBUTE", "TEXT", "CDATA_SECTION",
        "ENTITY_REFERENCE", "ENTITY", "PROCESSING_INSTRUCTION", "COMMENT", "DOCUMENT"};

    // Recursive walk over every node, printing its type and value
    static void walk(Node n, String indent) {
        String value = n.getNodeValue() == null ? "" : " \"" + n.getNodeValue()
                .replace("\n", "\\n") + "\"";
        System.out.println(indent + NAMES[n.getNodeType()] + " " + n.getNodeName() + value);
        if (n instanceof Element e) {
            NamedNodeMap attrs = e.getAttributes();
            for (int i = 0; i < attrs.getLength(); i++) {
                System.out.println(indent + "  @" + attrs.item(i).getNodeName() + "="
                        + attrs.item(i).getNodeValue());
            }
        }
        for (Node c = n.getFirstChild(); c != null; c = c.getNextSibling()) {
            walk(c, indent + "  ");
        }
    }

    static Document parse(boolean ignoreComments, boolean coalesce) throws Exception {
        DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
        f.setIgnoringComments(ignoreComments);
        f.setCoalescing(coalesce);                    // turn CDATA into ordinary text
        return f.newDocumentBuilder().parse(new InputSource(new StringReader(XML)));
    }

    public static void main(String[] args) throws Exception {
        Document doc = parse(false, false);
        walk(doc, "");

        Node body = doc.getElementsByTagName("body").item(0);
        System.out.println("body text content: " + body.getTextContent());
        System.out.println("body child nodes, default:            "
                + body.getChildNodes().getLength());
        Document merged = parse(true, true);
        Node body2 = merged.getElementsByTagName("body").item(0);
        System.out.println("body child nodes, coalescing:         "
                + body2.getChildNodes().getLength());
        System.out.println("note child nodes, ignoring comments:  "
                + merged.getDocumentElement().getChildNodes().getLength() + " (was "
                + doc.getDocumentElement().getChildNodes().getLength() + ")");

        // normalize() merges adjacent text nodes created by editing
        Element to = (Element) doc.getElementsByTagName("to").item(0);
        to.appendChild(doc.createTextNode(" and "));
        to.appendChild(doc.createTextNode("Ben"));
        System.out.print("<to> text nodes after appends: " + to.getChildNodes().getLength());
        doc.normalize();
        System.out.println(", after normalize(): " + to.getChildNodes().getLength() + " \""
                + to.getTextContent() + "\"");
    }
}

Output:

Output
DOCUMENT #document
  PROCESSING_INSTRUCTION report "style="short""
  ELEMENT note
    @id=n1
    @priority=high
    TEXT #text "\n  "
    COMMENT #comment " written by hand "
    TEXT #text "\n  "
    ELEMENT to
      TEXT #text "Ana"
    TEXT #text "\n  "
    ELEMENT body
      TEXT #text "Use "
      CDATA_SECTION #cdata-section "<b>bold</b> & more"
      TEXT #text " carefully"
    TEXT #text "\n"
body text content: Use <b>bold</b> & more carefully
body child nodes, default:            3
body child nodes, coalescing:         1
note child nodes, ignoring comments:  5 (was 7)
<to> text nodes after appends: 3, after normalize(): 1 "Ana and Ben"
  • The walk uses getFirstChild() and getNextSibling(), which visit each node once without building NodeLists. Attributes are not children: they are listed separately through getAttributes().
  • The processing instruction sits above the root element, as a child of the document. Text nodes contain the raw whitespace, shown as \n.
  • A CDATA section is its own node: <body> has 3 children, two text nodes around the CDATA. getTextContent() joins them, so <b>bold</b> & more comes back as literal text, never parsed as markup.
  • setCoalescing(true) turned the CDATA into ordinary text, merged into 1 child, and setIgnoringComments(true) removed the comment and the whitespace-only text node next to it, leaving 5 children of <note> instead of 7.
  • Appending text nodes left 3 separate nodes inside <to>. normalize() merged adjacent text nodes into one, "Ana and Ben", which code that reads getFirstChild().getNodeValue() depends on.

Namespaces

Real-world XML such as SOAP messages, invoices and Office files uses namespaces, which qualify element names with a URI so that two vocabularies can be mixed. The invoice below uses a prefixed namespace and a default one, and the program parses it twice, because the factory's default setting is the trap.

Java
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;

public class Namespaces {

    static final String XML = """
            <inv:invoice xmlns:inv="urn:example:invoice" xmlns="urn:example:common">
              <inv:number>INV-7</inv:number>
              <amount currency="EUR">120.00</amount>
            </inv:invoice>""";

    static Document parse(boolean namespaceAware) throws Exception {
        DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
        f.setNamespaceAware(namespaceAware);
        return f.newDocumentBuilder().parse(new InputSource(new StringReader(XML)));
    }

    public static void main(String[] args) throws Exception {
        for (boolean aware : new boolean[] {false, true}) {
            Document doc = parse(aware);
            Element root = doc.getDocumentElement();
            System.out.println("namespaceAware=" + aware);
            System.out.println("  root: tagName=" + root.getTagName() + ", localName="
                    + root.getLocalName() + ", namespace=" + root.getNamespaceURI());
            System.out.println("  getElementsByTagName(\"inv:number\"): "
                    + doc.getElementsByTagName("inv:number").getLength());
            System.out.println("  getElementsByTagNameNS(invoice ns, \"number\"): "
                    + doc.getElementsByTagNameNS("urn:example:invoice", "number").getLength());
            Element amount = (Element) doc.getElementsByTagName("amount").item(0);
            System.out.println("  <amount> namespace (default xmlns): "
                    + amount.getNamespaceURI());
        }
    }
}

Output:

Output
namespaceAware=false
  root: tagName=inv:invoice, localName=null, namespace=null
  getElementsByTagName("inv:number"): 1
  getElementsByTagNameNS(invoice ns, "number"): 0
  <amount> namespace (default xmlns): null
namespaceAware=true
  root: tagName=inv:invoice, localName=invoice, namespace=urn:example:invoice
  getElementsByTagName("inv:number"): 1
  getElementsByTagNameNS(invoice ns, "number"): 1
  <amount> namespace (default xmlns): urn:example:common
  • DocumentBuilderFactory is not namespace-aware by default. The root's local name and namespace were null, and getElementsByTagNameNS found 0 elements, even though the document is perfectly valid.
  • With setNamespaceAware(true), the root's local name is invoice in urn:example:invoice, the NS lookup found the number, and the unprefixed <amount> correctly belongs to the default namespace urn:example:common.
  • getElementsByTagName("inv:number") worked both times, because it matches the literal name including the prefix. That makes code depend on the prefix the sender chose, which namespaces explicitly allow to vary. Match on namespace URI and local name instead.

For queries over namespaced documents, see XPath, which needs the same setting.

Changing and writing XML

The tree can be edited in place: set text and attributes, create elements with doc.createElement, and attach them with appendChild or insertBefore. A Transformer then serializes the tree back to text.

Java
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;

public class DomModify {

    public static void main(String[] args) throws Exception {
        String xml = "<catalog><book id=\"b1\"><title>Effective Java</title>"
                + "<price>45.00</price></book></catalog>";
        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(new InputSource(new StringReader(xml)));

        // Change a value, add an attribute, insert an element, append a new book
        Element book = (Element) doc.getElementsByTagName("book").item(0);
        book.getElementsByTagName("price").item(0).setTextContent("39.99");
        book.setAttribute("onSale", "true");

        Element author = doc.createElement("author");
        author.setTextContent("Joshua Bloch & co");             // & is escaped on output
        book.insertBefore(author, book.getElementsByTagName("price").item(0));

        Element added = doc.createElement("book");
        added.setAttribute("id", "b2");
        Element title = doc.createElement("title");
        title.setTextContent("Java Concurrency in Practice");
        added.appendChild(title);
        doc.getDocumentElement().appendChild(added);

        // Serialize the tree with indentation
        Transformer t = TransformerFactory.newInstance().newTransformer();
        t.setOutputProperty(OutputKeys.INDENT, "yes");
        t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        StringWriter out = new StringWriter();
        t.transform(new DOMSource(doc), new StreamResult(out));
        System.out.print(out);
    }
}

Output:

Output
<catalog>
  <book id="b1" onSale="true">
    <title>Effective Java</title>
    <author>Joshua Bloch &amp; co</author>
    <price>39.99</price>
  </book>
  <book id="b2">
    <title>Java Concurrency in Practice</title>
  </book>
</catalog>
  • The price changed, the book gained an onSale attribute, and the author was inserted before the price, not at the end.
  • The & in the author's name was escaped to &amp; automatically. Building XML with DOM avoids the escaping bugs that string concatenation produces.
  • INDENT alone turns on line breaks; the indent width needs the extra indent-amount property of the JDK's built-in transformer.

The live NodeList trap

A NodeList returned by getElementsByTagName is live: it is a view of the tree, not a copy, and reflects every change as it happens. The program removes elements from a list of four items while looping over it, which is the most common way to hit this.

Java
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class LiveNodeList {

    static Document doc() throws Exception {
        String xml = "<items><item>a</item><item>b</item><item>c</item><item>d</item></items>";
        return DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(new InputSource(new StringReader(xml)));
    }

    static String remaining(Document d) {
        NodeList all = d.getElementsByTagName("item");
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < all.getLength(); i++) {
            sb.append(all.item(i).getTextContent());
        }
        return sb.length() + " left: " + sb;
    }

    public static void main(String[] args) throws Exception {
        // Trap: NodeLists are live, so removing while iterating forward skips nodes
        Document d1 = doc();
        NodeList items = d1.getElementsByTagName("item");
        System.out.println("length before: " + items.getLength());
        for (int i = 0; i < items.getLength(); i++) {
            Node n = items.item(i);
            n.getParentNode().removeChild(n);
        }
        System.out.println("remove all, forward loop:  " + remaining(d1));

        // Fix 1: iterate backwards
        Document d2 = doc();
        NodeList items2 = d2.getElementsByTagName("item");
        for (int i = items2.getLength() - 1; i >= 0; i--) {
            Node n = items2.item(i);
            n.getParentNode().removeChild(n);
        }
        System.out.println("remove all, backward loop: " + remaining(d2));

        // Fix 2: copy the nodes into an array first
        Document d3 = doc();
        NodeList items3 = d3.getElementsByTagName("item");
        Node[] copy = new Node[items3.getLength()];
        for (int i = 0; i < copy.length; i++) {
            copy[i] = items3.item(i);
        }
        for (Node n : copy) {
            if (!n.getTextContent().equals("c")) {
                n.getParentNode().removeChild(n);
            }
        }
        System.out.println("keep only c, from a copy:  " + remaining(d3));

        // Adding is affected too: the list grows while you loop over it
        Document d4 = doc();
        NodeList items4 = d4.getElementsByTagName("item");
        int before = items4.getLength();
        Element extra = d4.createElement("item");
        extra.setTextContent("e");
        d4.getDocumentElement().appendChild(extra);
        System.out.println("same NodeList after appendChild: " + before + " -> "
                + items4.getLength());
    }
}

Output:

Output
length before: 4
remove all, forward loop:  2 left: bd
remove all, backward loop: 0 left: 
keep only c, from a copy:  1 left: c
same NodeList after appendChild: 4 -> 5
  • The forward loop was meant to remove all four items but left 2, b and d. Removing item 0 shifted b into position 0 while the loop moved on to index 1, so every second element was skipped.
  • Looping backwards removes from the end, where the shift does not matter, and removed all four. Copying the nodes into an array first gives a stable snapshot for any kind of edit; keeping only c worked.
  • The list also grows: after appendChild, the same NodeList object reported 5 instead of 4. A loop that adds matching elements while iterating can therefore run forever.

Parsing untrusted XML safely

XML allows a document to declare entities that the parser replaces with other content, including the content of a file or URL. If an application parses XML from users with the default settings, an attacker can make the parser read local files or call internal URLs, an attack called XXE (XML External Entity). It was its own category, A4, in the OWASP Top 10 of 2017. The program writes a fake secret to a temporary file, parses a document whose entity points at it with a default and a hardened factory, and then tries an entity bomb.

Java
import java.io.StringReader;
import java.nio.file.Files;
import java.nio.file.Path;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;

public class SafeParsing {

    public static void main(String[] args) throws Exception {
        // A file the attacker should never be able to read through our parser
        Path secret = Files.createTempFile("server-secret", ".txt");
        Files.writeString(secret, "db.password=hunter2");

        // XML sent by an attacker: an external entity pointing at that file
        String evil = "<?xml version=\"1.0\"?>\n"
                + "<!DOCTYPE order [<!ENTITY x SYSTEM \"" + secret.toUri() + "\">]>\n"
                + "<order><note>&x;</note></order>";

        // Default factory: the entity is resolved and the file content ends up in the data
        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(new InputSource(new StringReader(evil)));
        System.out.println("default parser, <note> = "
                + doc.getElementsByTagName("note").item(0).getTextContent());

        // Hardened factory: refuse DOCTYPE declarations entirely
        DocumentBuilderFactory safe = DocumentBuilderFactory.newInstance();
        safe.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        safe.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        safe.setXIncludeAware(false);
        safe.setExpandEntityReferences(false);
        try {
            var builder = safe.newDocumentBuilder();
            builder.setErrorHandler(new DefaultHandler());   // throw instead of printing to stderr
            builder.parse(new InputSource(new StringReader(evil)));
        } catch (SAXParseException e) {
            System.out.println("hardened parser: SAXParseException, DOCTYPE is disallowed");
        }
        Files.delete(secret);

        // "Billion laughs": nested entities that expand to 10^9 copies of "lol"
        StringBuilder bomb = new StringBuilder("<?xml version=\"1.0\"?>\n<!DOCTYPE lolz [\n"
                + "<!ENTITY lol0 \"lol\">\n");
        for (int i = 1; i <= 9; i++) {
            bomb.append("<!ENTITY lol").append(i).append(" \"");
            for (int j = 0; j < 10; j++) {
                bomb.append("&lol").append(i - 1).append(';');
            }
            bomb.append("\">\n");
        }
        bomb.append("]>\n<lolz>&lol9;</lolz>");
        try {
            var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            builder.setErrorHandler(new DefaultHandler());
            builder.parse(new InputSource(new StringReader(bomb.toString())));
            System.out.println("billion laughs: parsed (unexpected)");
        } catch (SAXParseException e) {
            System.out.println("billion laughs, default parser: " + e.getMessage());
        }
    }
}

Output:

Output
default parser, <note> = db.password=hunter2
hardened parser: SAXParseException, DOCTYPE is disallowed
billion laughs, default parser: JAXP00010001: The parser has encountered more than "64000" entity expansions in this document; this is the limit imposed by the JDK.
  • The default parser placed the file's content into the <note> element, where the application would treat it as ordinary data, perhaps echoing it back to the attacker.
  • The hardened parser rejected the document because it contained a DOCTYPE. Disallowing DOCTYPE is the simplest complete defense, recommended by the OWASP XXE prevention cheat sheet, since normal data exchange documents never need one.
  • The "billion laughs" document defines ten levels of entities, each made of ten copies of the one below, so the last one expands to 109 copies of "lol", about 3 GB of text from a document under 1 KB. The JDK stopped it after 64,000 entity expansions, a limit it applies even to the default parser. Disallowing DOCTYPE blocks this attack as well, before any expansion.

The same risk applies to SAX, StAX, XPath and TransformerFactory; each has its own settings, shown on their pages.

How much memory a DOM tree uses

A tree of objects is much larger than the text it came from. The program builds a 4.6 MB document of 50,000 orders, times the parse (warm-up, then best of 3), and measures the heap held by the resulting tree before and after visiting every node. Heap figures come from Runtime after garbage collection, so they are approximate; this is a rough measurement on a 2-CPU Linux machine with JDK 21.

Java
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;

public class DomMemory {

    static long usedHeap() throws InterruptedException {
        Runtime rt = Runtime.getRuntime();
        for (int i = 0; i < 3; i++) {
            System.gc();
            Thread.sleep(100);
        }
        return rt.totalMemory() - rt.freeMemory();
    }

    static int count(org.w3c.dom.Node n) {
        int c = 1;
        for (org.w3c.dom.Node k = n.getFirstChild(); k != null; k = k.getNextSibling()) {
            c += count(k);
        }
        return c;
    }

    public static void main(String[] args) throws Exception {
        StringBuilder sb = new StringBuilder("<orders>\n");
        for (int i = 0; i < 50000; i++) {
            sb.append("  <order id=\"").append(i).append("\" status=\"")
                    .append(i % 3 == 0 ? "paid" : "open").append("\"><customer>user")
                    .append(i % 1000).append("</customer><total>").append(i % 500)
                    .append(".99</total></order>\n");
        }
        byte[] xml = sb.append("</orders>\n").toString().getBytes(StandardCharsets.UTF_8);
        System.out.printf("document: %,d orders, %.1f MB of XML%n", 50000,
                xml.length / 1e6);

        DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
        long best = Long.MAX_VALUE;
        Document doc = null;
        for (int run = 0; run < 4; run++) {                       // run 0 is a warm-up
            doc = null;
            long t0 = System.nanoTime();
            doc = f.newDocumentBuilder().parse(new ByteArrayInputStream(xml));
            if (run > 0) {
                best = Math.min(best, System.nanoTime() - t0);
            }
        }
        System.out.printf("parse time, best of 3: %d ms%n", best / 1000000);

        doc = null;
        long before = usedHeap();
        doc = f.newDocumentBuilder().parse(new ByteArrayInputStream(xml));
        long parsed = usedHeap();
        int nodes = count(doc);                                   // touch every node once
        long walked = usedHeap();
        System.out.printf("heap after parse:           about %3.0f MB (%.0fx the XML size)%n",
                (parsed - before) / 1e6, (parsed - before) / (double) xml.length);
        System.out.printf("heap after visiting %,d nodes: about %3.0f MB (%.0fx)%n", nodes,
                (walked - before) / 1e6, (walked - before) / (double) xml.length);
    }
}

Output (numbers will differ on your machine):

Output
document: 50,000 orders, 4.6 MB of XML
parse time, best of 3: 104 ms
heap after parse:           about  25 MB (6x the XML size)
heap after visiting 300,003 nodes: about  38 MB (8x)
  • Right after parsing, the tree held several times the size of the XML. After visiting all 300,003 nodes, the figure grew further, to about eight times. The JDK's Xerces-based parser stores the tree in a compact form and creates the full node objects the first time each one is touched, a technique Xerces calls deferred node expansion.
  • So a 100 MB file can need close to a gigabyte of heap as a DOM tree. For files of that size, use a streaming API such as StAX or SAX, which keep memory constant.
  • Parsing itself was quick, around a tenth of a second or less for 4.6 MB, so for small and medium documents the convenience of DOM costs little.

When to use DOM

XML APIs in the JDK
APIMemoryBest for
DOMWhole document as objects, several times the file sizeSmall and medium documents you need to navigate or change
SAXConstantLarge documents read once, callback style
StAXConstantLarge documents read or written with a simple loop
XPathUsually over a DOMFinding values with path expressions instead of loops
JAXBYour own objectsMapping documents with a fixed schema to Java classes

Whichever you choose: enable namespace awareness for namespaced documents, copy NodeLists before editing, and disallow DOCTYPE for input you did not create.