Java
XML
Pretty Print
Programming
Coding Tutorial

How to pretty print XML from Java?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Pretty-printing XML in Java usually means taking compact markup and writing it back with indentation and line breaks so humans can read it comfortably. The standard Java solution is to use a Transformer, and the right details are mostly about choosing the input form, preserving encoding expectations, and understanding that formatting can change whitespace presentation.

The Standard Approach: Transformer

If your XML is currently a string, you can feed it into a JAXP transformer and request indentation.

java
1import java.io.StringReader;
2import java.io.StringWriter;
3import javax.xml.transform.OutputKeys;
4import javax.xml.transform.Source;
5import javax.xml.transform.Transformer;
6import javax.xml.transform.TransformerFactory;
7import javax.xml.transform.stream.StreamResult;
8import javax.xml.transform.stream.StreamSource;
9
10public class PrettyXml {
11    public static String prettyPrint(String xml) throws Exception {
12        Source input = new StreamSource(new StringReader(xml));
13        StringWriter output = new StringWriter();
14
15        Transformer transformer = TransformerFactory.newInstance().newTransformer();
16        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
17        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
18        transformer.transform(input, new StreamResult(output));
19
20        return output.toString();
21    }
22
23    public static void main(String[] args) throws Exception {
24        String xml = "<root><user><name>Ada</name><role>admin</role></user></root>";
25        System.out.println(prettyPrint(xml));
26    }
27}

For many everyday Java programs, this is enough.

If You Already Have a DOM Document

If your code is already working with a parsed DOM tree, use DOMSource instead of reparsing from a string.

java
1import java.io.StringWriter;
2import javax.xml.transform.OutputKeys;
3import javax.xml.transform.Transformer;
4import javax.xml.transform.TransformerFactory;
5import javax.xml.transform.dom.DOMSource;
6import javax.xml.transform.stream.StreamResult;
7import org.w3c.dom.Document;
8
9public class PrettyDocument {
10    public static String prettyPrint(Document document) throws Exception {
11        Transformer transformer = TransformerFactory.newInstance().newTransformer();
12        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
13        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
14
15        StringWriter writer = new StringWriter();
16        transformer.transform(new DOMSource(document), new StreamResult(writer));
17        return writer.toString();
18    }
19}

This is cleaner when the XML has already been parsed and modified in memory.

Parsing First Can Improve Robustness

If the input XML might be malformed, parsing it first gives you a clearer failure mode than sending a broken string straight into a transform pipeline.

java
1import java.io.StringReader;
2import javax.xml.parsers.DocumentBuilderFactory;
3import org.w3c.dom.Document;
4import org.xml.sax.InputSource;
5
6public class ParseXml {
7    public static Document parse(String xml) throws Exception {
8        var factory = DocumentBuilderFactory.newInstance();
9        factory.setNamespaceAware(true);
10        return factory.newDocumentBuilder().parse(new InputSource(new StringReader(xml)));
11    }
12}

Then you can pretty-print the resulting Document using the earlier method.

Pretty Printing Is for Humans, Not Semantic Changes

Formatting changes do not usually alter XML meaning, but they can affect whitespace presentation in certain content models. That matters when text nodes intentionally contain significant spaces or line breaks.

So pretty printing is best used for:

  • logging
  • debugging
  • config display
  • developer-facing output

Be more cautious when rewriting XML that is sensitive to exact whitespace representation.

Writing to a File

Pretty printing often ends with writing the formatted output to disk.

java
1import java.nio.file.Files;
2import java.nio.file.Path;
3
4String formatted = PrettyXml.prettyPrint("<root><x>1</x><y>2</y></root>");
5Files.writeString(Path.of("output.xml"), formatted);

If you care about encoding, set the transformer output property and write the file using a matching character set strategy.

Third-Party Libraries Exist, but Start Simple

Libraries such as JDOM, DOM4J, and others can also format XML, but you do not need an extra dependency just to indent XML in a typical Java application. The built-in transformer approach is usually enough unless your XML-processing stack already relies on a different library.

Common Pitfalls

The biggest mistake is assuming pretty printing is always semantically harmless. In many cases it is, but whitespace-sensitive XML content deserves more care.

Another issue is forgetting that the input must still be well-formed XML. Pretty printing does not repair malformed markup.

Developers also sometimes mix string-based transformation and DOM-based transformation awkwardly. If you already have a Document, use DOMSource instead of converting back and forth unnecessarily.

Finally, do not hardcode formatting expectations too rigidly in tests. Different transformer implementations can vary slightly in the exact output layout while still producing valid indented XML.

Summary

  • In Java, pretty-printing XML is usually done with a Transformer.
  • Use StreamSource for XML strings and DOMSource for existing Document objects.
  • Indentation is controlled through transformer output properties.
  • Pretty printing is ideal for human readability, not for repairing malformed XML.
  • Be cautious when exact whitespace in XML content is significant.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.