Here you can find the source of writeDocument(Document document, String path)
public static void writeDocument(Document document, String path) throws Exception
//package com.java2s; //License from project: Open Source License import java.io.File; import java.io.FileOutputStream; import java.io.PrintWriter; 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 writeDocument(Document document, String path) throws Exception { TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); DOMSource source = new DOMSource(document); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); File file = new File(path); if (!file.exists()) { File parent = file.getParentFile(); if (!parent.exists()) { parent.mkdirs();//from w w w . j a v a 2 s.c o m } } PrintWriter writer = new PrintWriter(new FileOutputStream(path)); StreamResult result = new StreamResult(writer); transformer.transform(source, result); } }