PrintWriter wri = null;
try {
out = new FileOutputStream(file);
wri = new PrintWriter(new OutputStreamWriter(out, "UTF8"));
wri.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
(new DOMElementWriter()).write(doc.getDocumentElement(), wri, 0, " ");
wri.flush();
// writers do not throw exceptions, so check for them.
if (wri.checkError()){
throw new IOException("Error while writing DOM content");
}