Java Document to String

This is a very simple utility function to produce an indented XML document as a String given a Document. It throws a TransformerException if anything drastic goes wrong.

JAVA:
  1. import java.io.*;
  2. import org.w3c.dom.Document;
  3. import javax.xml.transform.*;
  4. import javax.xml.transform.dom.DOMSource;
  5.  
  6. ...
  7.  
  8. public static String documentToString( Document document ) throws TransformerException {
  9.     TransformerFactory tFactory = TransformerFactory.newInstance();
  10.     Transformer transformer = tFactory.newTransformer();
  11.    
  12.     DOMSource source = new DOMSource(document);
  13.     StringWriter sw = new StringWriter();
  14.     StreamResult result = new StreamResult(sw);
  15.    
  16.     transformer.setOutputProperty( OutputKeys.INDENT, "yes" );
  17.     transformer.transform(source, result);
  18.    
  19.     return sw.toString();
  20. }