tags:

views:

253

answers:

3

I have an xml document object that I need to convert into a string.

Is there as simple way to do this?

+1  A: 

You can use Dom4J:

OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter writer = new XMLWriter( System.out, format );
writer.write( document );
Todd R
+4  A: 

Here's some quick code I pulled out of a library I had nearby. Might wanna dress it up, but it works:

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

public String TransformDocumentToString(Document doc)
{
    DOMSource dom = new DOMSource(doc);
    StringWriter writer = new StringWriter();  
    StreamResult result = new StreamResult(writer);

    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer = factory.newTransformer();
    transformer.transform(dom, result);

    return writer.toString();
}

edit: as commentor noticed earlier, i had a syntax error. had to pull out some sensitive lines so I wouldn't get canned and put them back in the wrong order. thanks! ;-)

joshua.ewer
excellent... however it should be noted that you might (as I did) have an outdated version of xalan.jar, with which you will fail at the TransformerFactor.newInstance() call (even though it will not produce any errors in Eclipse).xalan-2.7.0.jar is the right version.
Dr.Dredel
A: 

I put this in the comment, but then thought that for future reference people might find it easier if I actually added it as an answer. So... Joshua.ewer's answer is correct, but requires xalan-2.7.0.jar.

Dr.Dredel
Good call. Thanks for pointing that out; I should have.
joshua.ewer