JavaRanch Home    
 
This page:         last edited 18 June 2010         What's Changed?         Edit

Document To File   

A frequent question is "Okay, I have a DOM, and I made some changes to it, now how do I write it out to an XML file?"

Here's a method that does that for a given org.w3c.dom.Node object (usually an instance of org.w3c.dom.Element or org.w3c.dom.Document):


import java.io.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.w3c.dom.*;
 
public class Util {
 
    public static void doc2file(Node node, String path) {
        try {
            Source source = new DOMSource(node);
            File out = new File(path);
            Result result = new StreamResult(out);
            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer = factory.newTransformer();
            transformer.transform(source, result);
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        }
    }
}

(See also DocumentToString)


XmlFaq CategoryCodeSamples

JavaRanchContact us — Copyright © 1998-2012 Paul Wheaton