I have an xml document object that I need to convert into a string.
Is there as simple way to do this?
I have an xml document object that I need to convert into a string.
Is there as simple way to do this?
You can use Dom4J:
OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter writer = new XMLWriter( System.out, format );
writer.write( document );
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! ;-)
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.