Pretty-printing an XML in Java

Imagine you want to format the following xml in a human-friendly format: test.xml:

<?xml version="1.0" encoding="UTF-8" ?> 
<message><content>Hello World!</content><destinations><dest>jmsqueue:myjmsqueue</dest>
<dest>file:/home/filequeue</dest><dest>123.30.230.90</dest></destinations></message>

You can do this using the XSLT transformer package. Working code sample: Main.java:

import org.w3c.dom.*;
 
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.*;
   
import java.io.*;
  
public class Main
{
   public static void main(String []args) {
      Document doc;
   
      try {
         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
         DocumentBuilder db = dbf.newDocumentBuilder();
         doc = db.parse(new File("test.xml"));
   
         // use the XSLT transformation package to output the subtree destinations
         Transformer transformer = TransformerFactory.newInstance().newTransformer();
         transformer.setOutputProperty(OutputKeys.METHOD, "xml");
         transformer.setOutputProperty(OutputKeys.INDENT, "yes"); 
         transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
          
         StringWriter sw = new StringWriter();
         transformer.transform(new DOMSource(doc), new StreamResult(sw));
          
         System.out.println(sw.toString());
      }
      catch(Exception e) {
         e.printStackTrace();
      }
   } 
}

outputs:

<?xml version="1.0" encoding="UTF-8"?>
<message>
  <content>Hello World!</content>
  <destinations>
    <dest>jmsqueue:myjmsqueue</dest>
    <dest>file:/home/filequeue</dest>
    <dest>123.30.230.90</dest>
  </destinations>
</message>