Pages

Friday, November 19, 2010

Write DOM Document to file in Java

There are times when you need to write a Java DOM Document to a file, lets say to save your data. Your Document may represent XML, HTML or any other markup language. Here is a simple function that will do the job:

/**
 * Saves a DOM Document to a file.
* @returns: True on success, false otherwise.
*/
public boolean saveDOMtoFile(Document doc, File myFile)
{
   try{
       TransformerFactory transformerFactory = TransformerFactory.newInstance();
       Transformer transformer = transformerFactory.newTransformer();
       DOMSource source = new DOMSource(doc);
       FileOutputStream out = new FileOutputStream(myFile);
       StreamResult result =  new StreamResult(out);
       transformer.transform(source, result);
       out.close();
  }catch(Exception e){ // You may catch exceptions individually if you wish
      //Something went wrong...
      return false;
 }
  return true;
}

You will also need to import any necessary packages. These should do:


import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.w3c.dom.*;
import java.io.*;

No comments:

Post a Comment