Java tutorial
//package com.java2s; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.Properties; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; public class Main { public static void output(Document doc, OutputStream outputStream) throws Exception { TransformerFactory tFactory = TransformerFactory.newInstance(); tFactory.setAttribute("indent-number", 4); Transformer transformer = tFactory.newTransformer(); Properties outputProperties = new Properties(); outputProperties.put(OutputKeys.INDENT, "yes"); outputProperties.put("{http://xml.apache.org/xslt}indent-amount", "4"); transformer.setOutputProperties(outputProperties); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new OutputStreamWriter(outputStream, "UTF-8")); transformer.transform(source, result); } }