Java tutorial
//package com.java2s; import java.io.OutputStream; 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; import org.w3c.dom.Element; public class Main { public static void marshalToStream(Document doc, OutputStream ostream, boolean indent) throws Exception { TransformerFactory transFac = TransformerFactory.newInstance(); Transformer trans = transFac.newTransformer(); if (indent) { trans.setOutputProperty(OutputKeys.INDENT, "yes"); trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); } trans.setOutputProperty(OutputKeys.STANDALONE, "no"); trans.transform(new DOMSource(doc), new StreamResult(ostream)); } public static void marshalToStream(Element elm, OutputStream ostream, boolean indent) throws Exception { TransformerFactory transFac = TransformerFactory.newInstance(); Transformer trans = transFac.newTransformer(); if (indent) { trans.setOutputProperty(OutputKeys.INDENT, "yes"); trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); } trans.setOutputProperty(OutputKeys.STANDALONE, "no"); trans.transform(new DOMSource(elm), new StreamResult(ostream)); } }