Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Using JDOM2, read a file, change the price of the book with id 2 to 25.00 and write the document back with pretty formatting.

We build the Document with a SAXBuilder configured not to process DTDs or expand entities, find the book with getRootElement().getChildren("book") and a stream filter on the id attribute, call book.getChild("price").setText("25.00"), and write the result with new XMLOutputter(Format.getPrettyFormat()). JDOM2 feels natural because it uses ordinary Java lists, generics and strings instead of W3C DOM's NodeList and node types.

Background to this question

JDOM2 is a popular open-source XML library designed for Java from the start, and it is common in older services and tools that edit configuration or data files. A small read, modify and write task shows whether we know its main classes and whether we remember to configure the parser safely, which older JDOM code often forgot. In this answer, we will recap the JDOM2 model, build the document securely, find and change the book, write it back with pretty formatting and the right encoding, and compare the experience with the W3C DOM API.

1A Quick Recap of the JDOM2 Model

JDOM2, in the org.jdom2 package, represents a parsed file as a Document with a root Element. Each Element has a name, attributes, text and child elements, and its children come back as a java.util.List<Element>, so we can loop, stream and filter them like any other collection. Text is a plain String. There is no separate node-type check for the common case, because getChildren() returns elements only.

JDOM2 does not parse XML itself. SAXBuilder uses a SAX parser underneath, usually the JDK's, to read the file and build the JDOM tree. XMLOutputter does the reverse, writing a tree as text with a Format that controls indentation, line endings and encoding.

2Building the Document Securely

A file we did not write ourselves could contain a DOCTYPE with external entities, the XXE attack in which the parser reads local files or calls internal URLs. Older JDOM2 versions processed external entities by default, and a vulnerability was fixed in 2.0.6.1, so we use a current version and also configure the builder explicitly.

Java
SAXBuilder builder = new SAXBuilder(XMLReaders.NONVALIDATING); // no DTD validation
builder.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); // reject DOCTYPE
builder.setExpandEntities(false); // never inline entity content
Document doc = builder.build(Path.of("books.xml").toFile());
// books.xml:
// <catalog>
// <book id="1"><title>Java Basics</title><price>19.00</price></book>
// <book id="2"><title>Spring in Depth</title><price>45.50</price></book>
// </catalog>

setFeature passes the feature to the underlying SAX parser; disallow-doctype-decl makes it reject any document with a DOCTYPE, which removes the whole family of entity attacks. If a format genuinely needs a DTD, we instead disable external general and parameter entities and keep setExpandEntities(false). Check the JDOM2 release notes for your version's defaults; configuring explicitly makes the code safe whatever they are.

3Finding the Book and Changing Its Price

Because children are a List<Element>, finding the book with id 2 is a short stream.

Java
Element catalog = doc.getRootElement();
Element book = catalog.getChildren("book").stream()
.filter(b -> "2".equals(b.getAttributeValue("id"))) // "2".equals(...) is null-safe
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("no book with id 2"));
Element price = book.getChild("price");
System.out.println(price.getText()); // 45.50
price.setText("25.00");
System.out.println(book.getChildText("price")); // 25.00
Step throughRead, modify and write with JDOM2
  1. SAXBuilder.build(file)DOCTYPE rejected, entities not expanded
  2. getRootElement().getChildren("book")List<Element>
  3. Book with id 2 found?
    YesChange price textNoThrow, leave the file untouched
  4. price.setText("25.00")tree changed in memory
  5. XMLOutputter with pretty formatwrite to a temp file, then move

5 steps in order. Play them, or step through them one at a time.

Notice two small defensive choices. We compare with "2".equals(...) so a book without an id attribute does not cause a NullPointerException, because getAttributeValue returns null when the attribute is missing. And we fail clearly with orElseThrow if the book does not exist, rather than writing back an unchanged file and pretending we succeeded. If the price element might be missing, getChild returns null, and we would add one with book.addContent(new Element("price").setText("25.00")).

If the file uses a namespace, getChildren("book") with a plain name only matches elements in no namespace; we then pass a Namespace object, getChildren("book", ns), with ns = Namespace.getNamespace("urn:catalog").

4Writing It Back With Pretty Formatting

XMLOutputter turns the tree into text. Format.getPrettyFormat() indents nested elements and puts each on its own line; the default encoding of a Format is UTF-8.

Java
XMLOutputter out = new XMLOutputter(Format.getPrettyFormat()); // indent " ", UTF-8
Path target = Path.of("books.xml");
Path tmp = Files.createTempFile(target.getParent(), "books", ".xml");
try (Writer w = Files.newBufferedWriter(tmp, StandardCharsets.UTF_8)) {
out.output(doc, w);
}
Files.move(tmp, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
// books.xml now:
// <?xml version="1.0" encoding="UTF-8"?>
// <catalog>
// <book id="1">
// <title>Java Basics</title>
// <price>19.00</price>
// </book>
// <book id="2">
// <title>Spring in Depth</title>
// <price>25.00</price>
// </book>
// </catalog>

Two details matter here. When we write to a Writer, the bytes are produced by the Writer's charset, while the XML declaration says what the Format's encoding is. If they disagree, for example a Writer in the platform charset and a declaration saying UTF-8, readers will misread any non-ASCII text. So we either open the Writer with the same charset as the Format, as above, or pass an OutputStream and let XMLOutputter encode. Second, writing to a temporary file and moving it into place means a crash halfway through never leaves a truncated books.xml behind.

5Why JDOM2 Feels Simpler Than W3C DOM

The same task with the JDK's W3C DOM needs a NodeList loop from 0 to getLength(), a check that each node is an Element, getElementsByTagName("price").item(0) for the child, and a Transformer with output properties to write the file. JDOM2 was designed around Java's own types: List<Element> with generics, String for text, method chaining for building elements, and a dedicated outputter. That is why many teams found it more pleasant for editing documents.

The trade-off is that JDOM2 is a third-party dependency with slower release activity than the JDK, so we must track its versions and security fixes ourselves, and like DOM it keeps the whole document in memory, so it suits files of modest size.

6Follow-up questions

Does pretty formatting change the meaning of the document?

It can, in documents where whitespace matters, such as mixed content or elements with significant spaces. Format.getPrettyFormat() trims and re-indents text. For data files like this catalog it is harmless; where whitespace matters we use Format.getRawFormat() or getCompactFormat() instead, or set the text mode explicitly.

Is a JDOM2 Document thread-safe?

No. Reading from several threads is safe only if nobody modifies it, and modifications must be confined to one thread. Builders and outputters are cheap enough to create per use, or we keep one per thread.

How would you use XPath with JDOM2?

JDOM2 has its own XPath support: XPathFactory.instance().compile("/catalog/book[@id='2']/price", Filters.element()) returns an XPathExpression<Element>, and evaluateFirst(doc) gives the price element directly, with typed results.

7Conclusion

In this answer, we built a JDOM2 Document with a SAXBuilder that rejects DOCTYPE declarations and does not expand entities, found the book with id 2 by streaming getRootElement().getChildren("book") and filtering on the id attribute, changed its price with getChild("price").setText("25.00"), and wrote the document back with XMLOutputter and Format.getPrettyFormat(), matching the Writer's charset to the declared encoding and replacing the file atomically. JDOM2's use of Java lists, generics and strings makes this shorter than W3C DOM code.

What to say in the interviewAbout 80 seconds aloud

Open with

I would create a SAXBuilder, using the non-validating reader factory, and configure it securely, because older JDOM versions processed external entities: I set the disallow-doctype-decl feature so any DOCTYPE is rejected, and setExpandEntities false.

Then, if they want more

Then builder.build on the file gives me a Document. To find the book, I take getRootElement().getChildren("book"), which is a normal List of Element, stream it, filter where "2".equals(getAttributeValue("id")), which is null-safe, and findFirst with orElseThrow so a missing book is an error instead of a silent no-op. Then book.getChild("price").setText("25.00"). If the price element could be missing I would add one.

To write it back, I create an XMLOutputter with Format.getPrettyFormat(), which indents and uses UTF-8, and output the document to a Writer opened with UTF-8 too, because the declaration and the actual bytes must agree. I would write to a temp file and move it over the original so a crash never leaves half a file.

What I like about JDOM2 is that it uses Java collections and generics, getChildren returns elements only, and text is just a String, compared with W3C DOM's NodeList loops and node-type checks. The cost is a third-party dependency we must keep patched, and the whole document is in memory.

About this answer

Last updated
12 November 2026
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 JDOM2, read a file, change the price of the book with id 2 to 25.00 and write the...": https://scrivio-interview-library.netlify.app/java/xml-processing/5dfcc0a1f3/