Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
// initialize StreamResult with File object to save to file
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
String xmlString = result.getWriter().toString();
System.out.println(xmlString);

Note: Results may vary depending on the Java version. Search for workarounds specific to your platform.

Answer from Lorenzo Boccaccia on Stack Overflow
Top answer
1 of 16
311
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
// initialize StreamResult with File object to save to file
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
String xmlString = result.getWriter().toString();
System.out.println(xmlString);

Note: Results may vary depending on the Java version. Search for workarounds specific to your platform.

2 of 16
146

a simpler solution based on this answer:

public static String prettyFormat(String input, int indent) {
    try {
        Source xmlInput = new StreamSource(new StringReader(input));
        StringWriter stringWriter = new StringWriter();
        StreamResult xmlOutput = new StreamResult(stringWriter);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setAttribute("indent-number", indent);
        transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
        transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");
        Transformer transformer = transformerFactory.newTransformer(); 
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(xmlInput, xmlOutput);
        return xmlOutput.getWriter().toString();
    } catch (Exception e) {
        throw new RuntimeException(e); // simple exception handling, please review it
    }
}

public static String prettyFormat(String input) {
    return prettyFormat(input, 2);
}

testcase:

prettyFormat("<root><child>aaa</child><child/></root>");

returns:

<?xml version="1.0" encoding="UTF-8"?>
<root>
  <child>aaa</child>
  <child/>
</root>

//Ignore: Original edit just needs missing s in the Class name in code. redundant six characters added to get over 6 characters validation on SO

🌐
Baeldung
baeldung.com › home › xml › pretty-print xml in java
Pretty-Print XML in Java | Baeldung
June 20, 2025 - If we want our pretty-print method to always generate the same format under various Java versions, we need to provide a stylesheet file. Next, let’s create a simple xsl file to achieve that. First, let’s create the prettyprint.xsl file to define the output format: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:strip-space elements="*"/> <xsl:output method="xml" encoding="UTF-8"/> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> </xsl:stylesheet>
🌐
Mkyong
mkyong.com › home › java › pretty print xml with java dom and xslt
Pretty Print XML with Java Dom and XSLT - Mkyong.com
May 16, 2021 - This article shows how to use Java DOM Parser + XSLT to format or pretty print a XML document.
🌐
W3Docs
w3docs.com › java
How to pretty print XML from Java?
Document xml = ...; // parse the XML document XmlUtils.prettyPrint(xml); ... This will pretty print the XML document to the console.
🌐
Novixys Software
novixys.com › blog › howto-pretty-print-xml-java
How to Pretty Print XML from Java? | Novixys Software Dev Blog
December 14, 2017 - DocumentBuilderFactory factory ... File(xmlFile)); Once the Document is obtained, you can transform it using the Transformer with suitable settings to pretty print the XML....
🌐
GitHub
gist.github.com › 1291393
XML Formatter/Pretty Printer Java · GitHub
XML Formatter/Pretty Printer Java. GitHub Gist: instantly share code, notes, and snippets.
🌐
Java Code Geeks
examples.javacodegeeks.com › home › java development › core java › xml › dom
Pretty print XML in Java - Java Code Geeks
June 27, 2013 - This is an example of how to pretty print an xml file in Java. We have implemented a method, that is void prettyPrint(Document xml), in order to transform the DOM Document to a formatted xml String.
Top answer
1 of 7
58

In reply to Espinosa's comment, here is a solution when "the original xml is not already (partially) indented or contain new lines".

Background

Excerpt from the article (see References below) inspiring this solution:

Based on the DOM specification, whitespaces outside the tags are perfectly valid and they are properly preserved. To remove them, we can use XPath’s normalize-space to locate all the whitespace nodes and remove them first.

Java Code

public static String toPrettyString(String xml, int indent) {
    try {
        // Turn xml string into a document
        Document document = DocumentBuilderFactory.newInstance()
                .newDocumentBuilder()
                .parse(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8"))));

        // Remove whitespaces outside tags
        document.normalize();
        XPath xPath = XPathFactory.newInstance().newXPath();
        NodeList nodeList = (NodeList) xPath.evaluate("//text()[normalize-space()='']",
                                                      document,
                                                      XPathConstants.NODESET);

        for (int i = 0; i < nodeList.getLength(); ++i) {
            Node node = nodeList.item(i);
            node.getParentNode().removeChild(node);
        }

        // Setup pretty print options
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setAttribute("indent-number", indent);
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        // Return pretty print xml string
        StringWriter stringWriter = new StringWriter();
        transformer.transform(new DOMSource(document), new StreamResult(stringWriter));
        return stringWriter.toString();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

Sample usage

String xml = "<root>" + //
             "\n   "  + //
             "\n<name>Coco Puff</name>" + //
             "\n        <total>10</total>    </root>";

System.out.println(toPrettyString(xml, 4));

Output

<root>
    <name>Coco Puff</name>
    <total>10</total>
</root>

References

  • Java: Properly Indenting XML String published on MyShittyCode
  • Save new XML node to file
2 of 7
10

I guess that the problem is related to blank text nodes (i.e. text nodes with only whitespaces) in the original file. You should try to programmatically remove them just after the parsing, using the following code. If you don't remove them, the Transformer is going to preserve them.

original.getDocumentElement().normalize();
XPathExpression xpath = XPathFactory.newInstance().newXPath().compile("//text()[normalize-space(.) = '']");
NodeList blankTextNodes = (NodeList) xpath.evaluate(original, XPathConstants.NODESET);

for (int i = 0; i < blankTextNodes.getLength(); i++) {
     blankTextNodes.item(i).getParentNode().removeChild(blankTextNodes.item(i));
}
Find elsewhere
🌐
Codemia
codemia.io › knowledge-hub › path › how_to_pretty_print_xml_from_java
How to pretty print XML from Java?
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises
🌐
Edureka Community
edureka.co › home › community › categories › java › how to pretty print xml from java
How to pretty print XML from Java | Edureka Community
July 4, 2018 - I have a Java String that contains XML, with no line feeds or indentations. I would like to turn it ... with nicely formatted XML. How do I do this?
🌐
Blogger
self-learning-java-tutorial.blogspot.com › 2018 › 03 › pretty-print-xml-string-in-java.html
Programming for beginners: Pretty print xml string in java
package com.sample.util; public class Test { public static void main(String args[]) throws Exception { String xmlData = "<?xml version=\"1.0\"?><!-- Represents Books information in store --><books><book id=\"1\"><name>Let Us C</name><author>Yashwant Kanetkar</author><price>245.00</price></book><book id=\"2\"><name>Let Us C++</name><author>Yashwant Kanetkar</author><price>252.00</price></book><book id=\"3\"><name>Java The Complete Reference</name><author>Herbert Schildt</author><price>489.00</price></book><book id=\"4\"><name>HTML5 Black Book</name><author>Kogent Learning Solutions</author><price>485.00</price></book></books>"; String str = XMLUtil.getPrettyString(xmlData, 2); System.out.println(str); } }
🌐
Coderanch
coderanch.com › wiki › 660141 › Pretty-Print-Xml-Java
How To Pretty Print Xml With Java (Wiki forum at Coderanch)
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums · this forum made possible by our volunteer staff, including ... ... Here's an example using the XMLSerializer class from Xerces: Here's an example using the JavaDoc:javax.xml.transformer.Transformer :
🌐
Victorjabur
victorjabur.com › 2020 › 02 › 19 › how-to-indent-xml-string-in-java-pretty
How to Indent XML String in Java (Pretty)
import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.apache.xml.serialize.OutputFormat; import org.apache.xml.serialize.XMLSerializer; import org.w3c.dom.Document; import org.xml.sax.InputSource; import org.xml.sax.SAXException; public class FormatXML { public static void main(String[] args) throws IOException, SAXException, ParserConfigurationException { System.out.println(format("YO
🌐
JSON Formatter
jsonformatter.org › xml-pretty-print
Best XML Pretty Print Online
XML Pretty Print is very unique tool for prettify json and pretty print XML data in color.
🌐
Delft Stack
delftstack.com › home › howto › java › java pretty print xml
How to Pretty Print XML in Java | Delft Stack
February 2, 2024 - To pretty-print XML in a file, we have to create an XML file and write the XML in that file using the pretty print way. See example: package delftstack; import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers...
🌐
Apache
oozie.apache.org › docs › 3.3.2 › core › apidocs › org › apache › oozie › util › XmlUtils.PrettyPrint.html
XmlUtils.PrettyPrint (Apache Oozie Core 3.3.2 API)
java.lang.Object org.apache.oozie.util.XmlUtils.PrettyPrint ... Pretty print string representation of an XML document that generates the pretty print on lazy mode when the toString() method is invoked.
🌐
Mrhaki
blog.mrhaki.com › 2012 › 10 › groovy-goodness-pretty-print-xml.html
Groovy Goodness: Pretty Print XML - Messages from mrhaki
November 1, 2013 - import groovy.xml.* def prettyXml = '''\<?xml version="1.0" encoding="UTF-8"?><languages> <language id="1">Groovy</language> <language id="2">Java</language> <language id="3">Scala</language> </languages> ''' // Pretty print a non-formatted XML String.
🌐
ConcretePage
concretepage.com › java › pretty-print-xml-java-transformer-xslt
Pretty Print XML with Java Transformer and XSLT
Source source = new StreamSource(new File("src/main/resources/inputFile.xml")); Result result = new StreamResult(new File("src/main/resources/outputFile.xml")); TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setAttribute("indent-number", 3); try { Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.transform(source, result); } catch (TransformerConfigurationException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } Find the output as pretty print XML.
🌐
Jee's Blog
vangjee.wordpress.com › 2009 › 02 › 25 › how-to-pretty-print-java-objects-to-xml
How to pretty print Java objects to XML | Jee’s Blog
March 16, 2009 - Introduction In this article, I will show how to pretty-print XML from Java objects. Generally and loosely speaking, the process of converting an object into a sequence of bits so that it can be st…