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.
import java.io.*;
import org.w3c.dom.Document;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
...
public static String documentToString( Document document ) throws TransformerException {
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
DOMSource source = new DOMSource(document);
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
transformer.setOutputProperty( OutputKeys.INDENT, "yes" );
transformer.transform(source, result);
return sw.toString();
}
About this entry
You’re currently reading “Java Document to String,” an entry on Weblog of Michael Cutler
- Published:
- 27th July 2005 / 12:07am
- Category:
- Java
No comments
Jump to comment form | comments rss [?] | trackback uri [?]