Here you can find the source of writeDoc(Document doc, File aFile)
public static String writeDoc(Document doc, File aFile)
//package com.java2s; //License from project: Creative Commons License import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import org.w3c.dom.Document; import com.sun.org.apache.xml.internal.serialize.OutputFormat; import com.sun.org.apache.xml.internal.serialize.XMLSerializer; public class Main { /** if aFile is given, will write to file, otherwise return as String */ public static String writeDoc(Document doc, File aFile) { String s = null;//from www . j ava 2 s . c o m try { OutputFormat format = new OutputFormat("XML", "UTF-8", true); if (aFile != null) { FileOutputStream out = new FileOutputStream(aFile); XMLSerializer serializer = new XMLSerializer(out, format); serializer.serialize(doc); out.close(); out.flush(); } else { ByteArrayOutputStream out = new ByteArrayOutputStream(); XMLSerializer serializer = new XMLSerializer(out, format); serializer.serialize(doc); out.close(); out.flush(); s = out.toString(); } } catch (Exception e) { throw new RuntimeException( "Exception while writing new XML document: \n", e); } return s; } }