XML Document to String

bluish picture bluish · Mar 28, 2011 · Viewed 170.4k times · Source

What's the simplest way to get the String representation of a XML Document (org.w3c.dom.Document)? That is all nodes will be on a single line.

As an example, from

<root>
  <a>trge</a>
  <b>156</b>
</root>

(this is only a tree representation, in my code it's a org.w3c.dom.Document object, so I can't treat it as a String)

to

"<root> <a>trge</a> <b>156</b> </root>"

Thanks!

Answer

WhiteFang34 picture WhiteFang34 · Mar 28, 2011

Assuming doc is your instance of org.w3c.dom.Document:

TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(doc), new StreamResult(writer));
String output = writer.getBuffer().toString().replaceAll("\n|\r", "");