How to convert a DOM Document object into an XML file using JAXP?

Chandra Patni

Using JAXP1.1 (See JSR 0063) javax.xml.transform.Transformer class can be used to convert a DOM Document object into an XML file. For example, writeToFile() method in the following snippet of code writes a Document object to a specified file. Note that javax.xml.transform is a new package defined in JAXP1.1.

import java.io.*;
import org.w3c.dom.Document;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;


public void writeToFile(Document doc, String fileNameToWrite) throws Exception {
    DOMSource domSource = new DOMSource(doc);
    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fileNameToWrite)));
    StreamResult streamResult = new StreamResult(out);
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.transform(domSource, streamResult);