Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Serialise a DOM Document to a String with indentation and UTF-8 encoding using the JDK Transformer API. What is a common surprise with indentation?

We create a Transformer with TransformerFactory.newInstance().newTransformer(), set OutputKeys.INDENT to yes and OutputKeys.ENCODING to UTF-8, and transform a DOMSource of the document into a StreamResult over a StringWriter. The common surprise is that INDENT alone does not control the indent amount; with the JDK's built-in transformer we set the implementation-specific property {http://xml.apache.org/xslt}indent-amount, and whitespace text nodes already in the DOM show up as extra blank lines.

Background to this question

Turning a DOM tree back into text is something every Java developer who touches XML needs, for logging, for sending a request or for writing a file. The JDK does it with the Transformer API from javax.xml.transform, which is really an XSLT engine running an identity transformation, and that origin explains its quirks. In this answer, we will recap what the Transformer does, write the method, look at the indentation surprises and how to fix them, clarify what the encoding setting really means when the result is a String, and secure the factory for untrusted input.

1A Quick Recap of the Transformer API

The javax.xml.transform package defines a general way to turn a Source into a Result, optionally applying an XSLT stylesheet. When we call newTransformer() without a stylesheet, we get an identity transformer: it copies the input to the output unchanged. Pairing a DOMSource (our in-memory document) with a StreamResult (a Writer or OutputStream) therefore serialises the DOM to text.

How the output looks is controlled by output properties, the same ones an XSLT stylesheet sets with xsl:output. OutputKeys gives us constants for the standard ones: INDENT, ENCODING, METHOD, OMIT_XML_DECLARATION and a few more.

2Writing the Method

Here is the straightforward version.

Java
static String toXmlString(Document doc) throws TransformerException {
TransformerFactory tf = TransformerFactory.newInstance();
tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); // no external DTDs
tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, ""); // no external stylesheets
Transformer t = tf.newTransformer();
t.setOutputProperty(OutputKeys.INDENT, "yes");
t.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); // JDK built-in transformer
StringWriter w = new StringWriter();
t.transform(new DOMSource(doc), new StreamResult(w));
return w.toString();
}
System.out.println(toXmlString(doc));
// <?xml version="1.0" encoding="UTF-8" standalone="no"?>
// <order id="7">
// <item>Pen</item>
// <item>Ink</item>
// </order>
Step throughWhat transform() does here
  1. DOMSource(doc)the in-memory tree
  2. Identity transformationcopy every node unchanged
  3. Apply output propertiesindent, encoding, declaration
  4. StreamResult(StringWriter)characters, not bytes
  5. w.toString()the XML text

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

The two setAttribute calls restrict external access. If the document or a stylesheet ever refers to an external DTD or stylesheet, the transformer will refuse to fetch it rather than reading a file or calling a URL. This matters when the input came from outside, and it costs nothing when it did not. A Transformer is not thread-safe, so we create one per call or per thread; the factory can be reused if only one thread configures it.

3The Indentation Surprises

The first surprise is that INDENT=yes is only a request. The XSLT specification lets the processor decide how much to indent, and the JDK's built-in transformer, a copy of Apache Xalan, has historically used zero spaces by default in older versions, producing line breaks without visible indentation; newer JDKs use a small default. The portable way to get what we want is the vendor-specific property {http://xml.apache.org/xslt}indent-amount, which the built-in transformer understands. If another implementation, such as Saxon, is on the classpath and gets picked up by TransformerFactory.newInstance(), that property may be ignored and we use its own settings, so check which implementation you get.

The second surprise appears when the document was parsed from a pretty-printed file. The DOM then already contains whitespace text nodes between elements, and the transformer keeps them, because to an identity transformation they are data. Since around Java 9, the built-in transformer also adds its own indentation around them, and the result is extra blank lines between elements.

Java
// doc parsed from an already indented file, then serialised with INDENT=yes:
// <order id="7">
//
// <item>Pen</item>
//
// <item>Ink</item>
//
// </order>
// Fix: remove whitespace-only text nodes before serialising
XPath xp = XPathFactory.newInstance().newXPath();
NodeList blanks = (NodeList) xp.evaluate("//text()[normalize-space() = '']", doc, XPathConstants.NODESET);
for (int i = 0; i < blanks.getLength(); i++) {
Node n = blanks.item(i);
n.getParentNode().removeChild(n);
}
System.out.println(toXmlString(doc)); // clean indentation again

We either strip the whitespace-only text nodes first, as above, or accept the output, or skip INDENT for documents that already have their own formatting. Stripping is safe for data documents but would damage mixed content, where spaces between elements are part of the text.

4What the Encoding Setting Means for a String

OutputKeys.ENCODING tells the transformer which encoding to declare and, when writing to an OutputStream, which charset to use for the bytes. But a StringWriter holds characters, not bytes. So with a StringWriter the setting only affects the declaration, and the string says encoding="UTF-8" even though it is a Java String. The real encoding is decided later, when that string is written somewhere. If we then save it with a Writer in another charset, the declaration lies, and readers will misread non-ASCII characters such as U+00E9.

When the destination is a file or a network stream, it is better to pass the OutputStream to StreamResult directly, so the transformer encodes the bytes in the declared encoding. Two smaller cosmetic details are also common: the declaration includes standalone="no" unless we call doc.setXmlStandalone(true), and if we do not want a declaration at all, for example when embedding the XML in a log line, we set OutputKeys.OMIT_XML_DECLARATION to yes.

5Follow-up questions

Why use a Transformer at all instead of a library method?

The JDK has no simpler built-in DOM serialiser in its public API; the Transformer is the standard way. The older LSSerializer from DOM Level 3 Load and Save also works, through DOMImplementationLS, and has a format-pretty-print parameter, but it is less commonly used. Libraries such as JDOM2 offer friendlier outputters.

Is it safe to transform untrusted XML with a user-supplied stylesheet?

Not without care. An XSLT stylesheet is a program: it can load documents, and some processors allow extension functions that call Java. We should enable FEATURE_SECURE_PROCESSING on the factory, restrict ACCESS_EXTERNAL_DTD and ACCESS_EXTERNAL_STYLESHEET, and ideally never run stylesheets that users write.

How can I serialise only part of the document?

Pass the element instead of the document: new DOMSource(element). The transformer serialises that subtree. Set OMIT_XML_DECLARATION to yes if the fragment is going to be embedded in something else.

6Conclusion

In this answer, we serialised a DOM Document to a String with an identity Transformer, setting INDENT and ENCODING through OutputKeys and transforming a DOMSource into a StreamResult over a StringWriter. We saw that the indent amount needs the {http://xml.apache.org/xslt}indent-amount property with the JDK's built-in transformer, that existing whitespace text nodes create blank lines unless we strip them, that ENCODING only changes the declaration when the result is a String, and that ACCESS_EXTERNAL_DTD and ACCESS_EXTERNAL_STYLESHEET should be set to empty for untrusted input.

What to say in the interviewAbout 80 seconds aloud

Open with

I would get a Transformer from TransformerFactory.newInstance().newTransformer(), which without a stylesheet is an identity transform, so it just copies the DOM to the output. I set OutputKeys.INDENT to yes and OutputKeys.ENCODING to UTF-8, create a StringWriter, call transform with a new DOMSource of the document and a new StreamResult of the writer, and return writer.toString().

Then, if they want more

On the factory I set ACCESS_EXTERNAL_DTD and ACCESS_EXTERNAL_STYLESHEET to the empty string, so it never fetches anything external if the input is untrusted. The common surprise is indentation.

INDENT yes only requests indentation; the amount is up to the implementation, and with the JDK's built-in Xalan-based transformer you set the vendor property curly brace http xml.apache.org xslt curly brace indent-amount to get, say, two spaces.

The second surprise is blank lines: if the document was parsed from a pretty-printed file, it already has whitespace text nodes, and newer JDKs re-indent around them, so you get empty lines. I strip whitespace-only text nodes first, for example with an XPath for text nodes whose normalize-space is empty, or accept the output.

I would also mention that with a StringWriter the encoding only affects the declaration, since a String has no bytes; when writing to a file, pass the OutputStream instead.

About this answer

Last updated
12 November 2026
Versions it names
Java 9
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 "Serialise a DOM Document to a String with indentation and UTF-8 encoding using the JDK...": https://scrivio-interview-library.netlify.app/java/xml-processing/9797d75ea9/