Is there a more elegant way to convert an XML Document to a String in Java than this code?

Here is the code currently used.

public String getStringFromDoc(org.w3c.dom.Document doc)    {
           DOMSource domSource = new DOMSource(doc);
           StringWriter writer = new StringWriter();
           StreamResult result = new StreamResult(writer);
           TransformerFactory tf = TransformerFactory.newInstance();
           Transformer transformer = tf.newTransformer();
           transformer.transform(domSource, result);
           return writer.toString();
        catch(TransformerException ex)
           return null;


Relies on DOM Level3 Load/Save:

public String getStringFromDoc(org.w3c.dom.Document doc)    {
    DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation();
    LSSerializer lsSerializer = domImplementation.createLSSerializer();
    return lsSerializer.writeToString(doc);   

This is a little more concise:

try {
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    StreamResult result = new StreamResult(new StringWriter());
    DOMSource source = new DOMSource(doc);
    transformer.transform(source, result);
    return result.getWriter().toString();
} catch(TransformerException ex) {
    return null;

Otherwise you could use a library like XMLSerializer from Apache:

//Serialize DOM
OutputFormat format    = new OutputFormat (doc); 
// as a String
StringWriter stringOut = new StringWriter ();    
XMLSerializer serial   = new XMLSerializer (stringOut,format);
// Display the XML

The transformer API is the only XML-standard way to transform from a DOM object to a serialized form (String in this case). As standard I mean SUN Java XML API for XML Processing.

Other alternatives such as Xerces XMLSerializer or JDOM XMLOutputter are more direct methods (less code) but they are framework-specific.

In my opinion the way you have used is the most elegant and most portable of all. By using a standard XML Java API you can plug the XML-Parser or XML-Transformer of your choice without changing the code(the same as JDBC drivers). Is there anything more elegant than that?

You could use XOM to perhaps do this:

org.w3c.dom.Document domDocument = ...;
nu.xom.Document xomDocument = 
String xml = xomDocument.toXML();

Need Your Help

plot3d - how to change box color and remove axis ticks

r rgl

I'm trying to make some visual modifications to the default plot3d object. Specifically i would like to put a light box color as a background (only in the box, not the whole palette) and remove the...

Get email address from Outlook email outlook

I am trying to output the email address of the current user through an Outlook addon. I haven't been able to get any other examples to work. The closest I have come is: