JavaRanch Home    
This page:         last edited 17 March 2007         What's Changed?         Edit

Document To String   

Another common question is how one gets a string representation of a given DOM object.

Here's a method that returns the string representation of a given org.w3c.dom.Node object (usually an instance of org.w3c.dom.Element or org.w3c.dom.Document):

import org.w3c.dom.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
public class Util {
    public static String xmlToString(Node node) {
        try {
            Source source = new DOMSource(node);
            StringWriter stringWriter = new StringWriter();
            Result result = new StreamResult(stringWriter);
            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer = factory.newTransformer();
            transformer.transform(source, result);
            return stringWriter.getBuffer().toString();
        } catch (TransformerConfigurationException e) {
        } catch (TransformerException e) {
        return null;

XmlFaq CategoryCodeSamples

JavaRanchContact us — Copyright © 1998-2014 Paul Wheaton