Java tutorial
//package com.java2s; import org.w3c.dom.Document; import javax.xml.transform.*; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import java.io.*; public class Main { public static void pretty(Document document, OutputStream outputStream, int indent) throws IOException { TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = null; try { transformer = transformerFactory.newTransformer(); } catch (TransformerConfigurationException e) { throw new RuntimeException(e); } transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); if (indent > 0) { transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", Integer.toString(indent)); } Result result = new StreamResult(outputStream); Source source = new DOMSource(document); try { transformer.transform(source, result); } catch (TransformerException e) { throw new IOException(e); } } }