Java org.w3c.dom.Document output nicely formatted

This will print a nicely formatted (indented, linebreaks etc) i.e. more human readable xml document.

public static String getNiceLyFormattedXMLDocument(Document doc) throws IOException, TransformerException {
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
 
    Writer stringWriter = new StringWriter();
    StreamResult streamResult = new StreamResult(stringWriter);
    transformer.transform(new DOMSource(doc), streamResult);
    String result = stringWriter.toString();
 
    return result;
}