Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Using the JDK DOM API, parse this file and print each book title with its price as a BigDecimal: <catalog><book id="1"><title>Java</title><price>39.90</price></book><book id="2"><title>SQL</title><price>29.50</price></book></catalog>

Create a DocumentBuilderFactory, configure it securely (secure processing on, DOCTYPE declarations disallowed), get a DocumentBuilder and parse the file into a Document. Then loop over doc.getElementsByTagName("book"), cast each node to Element, read the id with getAttribute("id") and the child text with getElementsByTagName("title").item(0).getTextContent(), and turn the price into new BigDecimal(text.trim()), never a double. A DocumentBuilder is not thread-safe, so we create one per use or per thread; a configured factory can be shared.

Why this question is asked

XML is still everywhere in Java systems: configuration files, bank and insurance messages, SOAP services, product catalogues from suppliers. The JDK's DOM API is the tool that is always available, and interviewers ask this exercise to check three things at once: that we can navigate a DOM tree, that we parse safely, and that we handle money correctly. In this answer, we will recap what DOM is, set up the parser securely, write the loop that prints titles and prices, see why BigDecimal matters, discuss thread safety, and answer what getTextContent() returns for an element with children.

1A Quick Recap of the DOM Model

DOM, the Document Object Model, parses the whole XML document into a tree of nodes in memory. The document node is the root; below it are element nodes such as catalog and book, attribute nodes such as id, and text nodes holding the characters between tags, such as Java or 39.90. Notice that the text inside an element is not a property of the element itself but a separate child node.

Because the whole tree is in memory, DOM is easy to navigate in any direction and suits small to medium documents, such as this catalogue. For files of hundreds of megabytes, a streaming API such as StAX is the better choice, because DOM can need several times the file size in heap.

2Setting Up a Secure Parser

We obtain a parser through a factory. The important step, often forgotten, is to configure the factory securely before using it. By default, XML parsers may process a DOCTYPE with external entities, which lets a malicious document read local files or make network requests from our server, an attack called XXE, XML external entity injection. Disallowing DOCTYPE declarations entirely is the simplest and safest setting when our documents do not need one, as here.

Java
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
f.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); // limits on entity expansion and more
f.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); // no DOCTYPE: blocks XXE
f.setXIncludeAware(false);
f.setExpandEntityReferences(false);
DocumentBuilder b = f.newDocumentBuilder();
Document doc = b.parse(new File("catalog.xml")); // whole tree in memory
doc.getDocumentElement().normalize(); // merge adjacent text nodes

With disallow-doctype-decl set, a document that contains a DOCTYPE fails to parse with a SAXParseException instead of being processed, which is exactly what we want for untrusted input. The feature name shown is the one understood by the JDK's built-in parser, which is based on Xerces; other parsers on the class path may differ, so check which implementation you get.

3Reading Titles, Prices and Ids

Now we navigate the tree. getElementsByTagName("book") returns a NodeList of every book element in the document, in document order. A NodeList is not a java.util.List, so we loop with an index from 0 to getLength() and fetch each node with item(i). Each node is typed as Node, so we cast it to Element to use element methods such as getAttribute().

Java
import java.math.BigDecimal;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
NodeList books = doc.getElementsByTagName("book");
for (int i = 0; i < books.getLength(); i++) {
Element book = (Element) books.item(i);
String id = book.getAttribute("id"); // "1"
String title = book.getElementsByTagName("title").item(0).getTextContent(); // "Java"
String priceText = book.getElementsByTagName("price").item(0).getTextContent(); // "39.90"
BigDecimal price = new BigDecimal(priceText.trim()); // 39.90, exact
System.out.println(id + " " + title + " " + price);
}
// 1 Java 39.90
// 2 SQL 29.50
Step throughThe DOM tree for the first book
  1. Documentthe whole file
  2. Element catalogdocument element
  3. Element bookattribute id = "1"
  4. Element title / Element pricechildren of book
  5. Text "Java" / Text "39.90"text nodes: what getTextContent() returns

5 layers, from the top down. Step through them one at a time.

Text is a child node of the element, which is why we ask the element for its text content.

Notice that we call getElementsByTagName on the book element, not on the document, so it only searches inside this book. It searches all descendants, not only direct children, which is fine here but worth knowing for nested structures. getAttribute returns an empty string, not null, when the attribute is missing. And item(0) returns null if there is no title element at all, so for untrusted input we would check for null before calling getTextContent(). We call trim() because a pretty-printed file may have spaces or line breaks around the number, and new BigDecimal(" 39.90") would throw a NumberFormatException.

4Why BigDecimal and Not double

Prices are money, and money must be exact. A double stores numbers in binary, and most decimal fractions, such as 0.10 or 39.90, have no exact binary representation. The errors are tiny, but they show up in sums and comparisons.

Java
double a = Double.parseDouble("39.90");
double b = Double.parseDouble("29.50");
System.out.println(a + b); // 69.4
System.out.println(0.1 + 0.2); // 0.30000000000000004
BigDecimal x = new BigDecimal("39.90");
BigDecimal y = new BigDecimal("29.50");
System.out.println(x.add(y)); // 69.40, exact, scale 2 kept
System.out.println(new BigDecimal("39.90").equals(new BigDecimal("39.9"))); // false: scale differs
System.out.println(new BigDecimal("39.90").compareTo(new BigDecimal("39.9"))); // 0: same value

So we create the BigDecimal from the string, never from a double, because new BigDecimal(39.90) would capture the binary error exactly. Notice too that equals() compares scale as well as value, so compareTo() is the right way to compare amounts.

5Thread Safety of the Factory and the Builder

A DocumentBuilder is not thread-safe: it keeps parsing state, so two threads parsing with the same builder at the same time can corrupt each other's results. The usual pattern is to configure the factory once, share it, and create a new builder for each parse, or keep one builder per thread. Creating a builder is cheap compared with parsing. Strictly, the JAXP specification does not guarantee that the factory itself is thread-safe either, so the safest approach is to finish configuring it once at startup and only call newDocumentBuilder() on it afterwards, synchronising that call or using a ThreadLocal<DocumentBuilder> if in doubt. A builder can also be reused by the same thread after calling reset().

6Follow-up questions

What does getTextContent return for an element with child elements?

It returns the concatenated text of all descendant text nodes, in document order, with no separators, and it ignores comments and processing instructions. For our first book, book.getTextContent() returns "Java39.90" because the file has no whitespace between tags; in a pretty-printed file it would also include the line breaks and indentation, such as a newline and spaces before Java. That is why we ask the specific child element for its text.

Why does getElementsByTagName sometimes return more than expected?

Because it matches all descendants with that name, at any depth, not just direct children. If a book contained a nested series element with its own title, book.getElementsByTagName("title") would return both. To read only direct children, loop over getChildNodes() and check each node's type and name, or use XPath with an expression such as ./title.

When would you use XPath instead?

XPath is convenient for selecting nodes by path or condition, for example //book[@id='2']/price. The JDK includes javax.xml.xpath, which works on the same Document. For simple, fixed structures like this one, plain DOM navigation is clear and fast; for complex queries, XPath is shorter and easier to read.

7Conclusion

In this answer, we parsed the catalogue with the JDK DOM API: a DocumentBuilderFactory configured for secure processing and with DOCTYPE declarations disallowed, a DocumentBuilder that parses the file into a Document, a loop over getElementsByTagName("book") with each node cast to Element, getAttribute for the id and getTextContent for the child text, and new BigDecimal(text.trim()) for prices. We also saw that a DocumentBuilder is not thread-safe while a configured factory can be shared, and what getTextContent returns for an element with children.

What to say in the interviewAbout 80 seconds aloud

Open with

I would start with DocumentBuilderFactory newInstance, and before anything else configure it securely: secure processing on, and the disallow-doctype-decl feature set to true, which blocks XXE attacks because a document with a DOCTYPE simply fails to parse.

Then, if they want more

Then newDocumentBuilder, parse the file into a Document, and normalize the document element. To read the books, I call doc getElementsByTagName book, which gives a NodeList, loop with an index up to getLength, and cast each item to Element.

On each book I call getAttribute id for the id, and getElementsByTagName title, item zero, getTextContent for the title, and the same for price.

The price I convert with new BigDecimal of the trimmed text, never Double parseDouble, because doubles cannot represent values like 39.90 exactly and errors appear in sums; and I compare amounts with compareTo, since equals also compares scale. For untrusted input I would check that item zero is not null.

On threading: a DocumentBuilder holds parsing state and is not thread-safe, so I create one per parse or per thread, while the configured factory is shared. And if asked about getTextContent on an element with children: it concatenates all descendant text, so the whole book gives Java39.90.

About this answer

Last updated
12 November 2026
Versions it names
Java 39
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Using the JDK DOM API, parse this file and print each book title with its price as a...": https://scrivio-interview-library.netlify.app/java/xml-processing/17039c4307/