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.
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.xmlDocumentBuilderFactory.newInstance()org.w3c.dom
| Interface | Node type constant | Example |
|---|---|---|
Document | DOCUMENT_NODE | The root of the tree, above the root element |
Element | ELEMENT_NODE | <book id="b1"> |
Attr | ATTRIBUTE_NODE | id="b1" |
Text | TEXT_NODE | Character data, including whitespace between elements |
CDATASection | CDATA_SECTION_NODE | <![CDATA[a < b]]> |
ProcessingInstruction | PROCESSING_INSTRUCTION_NODE | <?report style="short"?> |
Comment | COMMENT_NODE | <!-- note --> |
All programs use only the JDK and were run on JDK 21.
Reading a document
DocumentBuilderFactoryparseDocument
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:
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
finds matching elements anywhere below the node it is called on, sogetElementsByTagName stays inside that one book.book.getElementsByTagName("price") returns all the text inside an element, including that of nested elements.getTextContent ongetChildNodes 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<catalog> , a frequent source ofgetNodeType() .ClassCastException returns an empty string, notgetAttribute , for a missing attribute; usenull to tell the difference.hasAttribute
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.
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:
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
andgetFirstChild() , which visit each node once without buildinggetNextSibling() s. Attributes are not children: they are listed separately throughNodeList .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:
has 3 children, two text nodes around the CDATA.<body> joins them, sogetTextContent() comes back as literal text, never parsed as markup.<b>bold</b> & more turned the CDATA into ordinary text, merged into 1 child, andsetCoalescing(true) removed the comment and the whitespace-only text node next to it, leaving 5 children ofsetIgnoringComments(true) instead of 7.<note>- Appending text nodes left 3 separate nodes inside
.<to> merged adjacent text nodes into one, "Ana and Ben", which code that readsnormalize() depends on.getFirstChild().getNodeValue()
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.
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:
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
is not namespace-aware by default. The root's local name and namespace wereDocumentBuilderFactory , andnull found 0 elements, even though the document is perfectly valid.getElementsByTagNameNS- With
, the root's local name issetNamespaceAware(true) ininvoice , the NS lookup found the number, and the unprefixedurn:example:invoice correctly belongs to the default namespace<amount> .urn:example:common 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.getElementsByTagName("inv:number")
For queries over namespaced documents, see
Changing and writing XML
The tree can be edited in place: set text and attributes, create elements with doc.createElementappendChildinsertBeforeTransformer
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:
<catalog>
<book id="b1" onSale="true">
<title>Effective Java</title>
<author>Joshua Bloch & 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
attribute, and the author was inserted before the price, not at the end.onSale - The
in the author's name was escaped to& automatically. Building XML with DOM avoids the escaping bugs that string concatenation produces.& alone turns on line breaks; the indent width needs the extraINDENT property of the JDK's built-in transformer.indent-amount
The live NodeList trap
A NodeListgetElementsByTagName
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:
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,
andb . Removing item 0 shiftedd into position 0 while the loop moved on to index 1, so every second element was skipped.b - 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
worked.c - The list also grows: after
, the sameappendChild object reported 5 instead of 4. A loop that adds matching elements while iterating can therefore run forever.NodeList
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.
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:
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
element, where the application would treat it as ordinary data, perhaps echoing it back to the attacker.<note> - The hardened parser rejected the document because it contained a
. DisallowingDOCTYPE is the simplest complete defense, recommended by the OWASP XXE prevention cheat sheet, since normal data exchange documents never need one.DOCTYPE - 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
blocks this attack as well, before any expansion.DOCTYPE
The same risk applies to SAX, StAX, XPath and TransformerFactory
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
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):
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 orSAX , 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
| API | Memory | Best for |
|---|---|---|
| DOM | Whole document as objects, several times the file size | Small and medium documents you need to navigate or change |
| Constant | Large documents read once, callback style | |
| Constant | Large documents read or written with a simple loop | |
| Usually over a DOM | Finding values with path expressions instead of loops | |
| Your own objects | Mapping documents with a fixed schema to Java classes |
Whichever you choose: enable namespace awareness for namespaced documents, copy NodeListDOCTYPE