Java tutorial
//package com.java2s; //License from project: Apache License import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.util.Properties; 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 { /** * @param dom * @param outFile */ public static void writeDomToFile(Document dom, File outFile) { try { TransformerFactory transFact = TransformerFactory.newInstance(); Transformer transformer = transFact.newTransformer(); DOMSource source = new DOMSource(dom); StreamResult result; result = new StreamResult( new OutputStreamWriter(new FileOutputStream(outFile), System.getProperty("file.encoding"))); transformer.transform(source, result); } catch (Exception e) { throw new RuntimeException( "Could not write dom tree '" + dom.getBaseURI() + "' to file '" + outFile.getName() + "'!", e); } } public static void writeDomToFile(Document dom, File outFile, Properties outputProperties) { // try { // StringWriter ret = new StringWriter(); // TransformerFactory transFact = TransformerFactory.newInstance(); //// transFact.setAttribute("indent-number", 2); // Transformer transformer = transFact.newTransformer(); // if (outputProperties != null) transformer.setOutputProperties(outputProperties); // DOMSource source = new DOMSource(dom); // StreamResult result = new StreamResult(ret); try { TransformerFactory transFact = TransformerFactory.newInstance(); Transformer transformer = transFact.newTransformer(); if (outputProperties != null) transformer.setOutputProperties(outputProperties); DOMSource source = new DOMSource(dom); StreamResult result; result = new StreamResult( new OutputStreamWriter(new FileOutputStream(outFile), System.getProperty("file.encoding"))); transformer.transform(source, result); } catch (Exception e) { throw new RuntimeException( "Could not write dom tree '" + dom.getBaseURI() + "' to file '" + outFile.getName() + "'!", e); } } /** * @param dom * @param outFile */ public static void writeDomToFile(Element dom, File outFile) { try { TransformerFactory transFact = TransformerFactory.newInstance(); Transformer transformer = transFact.newTransformer(); DOMSource source = new DOMSource(dom); StreamResult result; result = new StreamResult( new OutputStreamWriter(new FileOutputStream(outFile), System.getProperty("file.encoding"))); transformer.transform(source, result); } catch (Exception e) { throw new RuntimeException( "Could not write dom tree '" + dom.getBaseURI() + "' to file '" + outFile.getName() + "'!", e); } } }