Java tutorial
//package com.java2s; import java.io.IOException; import java.io.OutputStream; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; 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 { /** * write out an XML file * * @param doc * @param os * @throws TransformerException * @throws IOException */ public static void writeXML(Document doc, OutputStream os) throws TransformerException, IOException { // write out xml file TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); //indent XML properly //formatXML(doc,doc.getDocumentElement()," "); //normalize document doc.getDocumentElement().normalize(); //write XML to file DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(os); transformer.transform(source, result); os.close(); } }