Take the 2-minute tour ×

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


(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)


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


share|improve this question
Dupe of stackoverflow.com/questions/315517/… –  james.garriss Aug 1 '13 at 15:50
@AshishAggarwal Thanks, but would be better if you post your solution as an answer (instead of a comment) and give us a summary of it (instead of just a link) ;) –  bluish Jan 14 at 13:31

3 Answers 3

up vote 78 down vote accepted

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", "");
share|improve this answer
+1, that's neat! –  Oliver Shaw Apr 7 at 21:27

Use the Apache XMLSerializer

here's an example: http://www.informit.com/articles/article.asp?p=31349&seqNum=3&rl=1

you can check this as well


share|improve this answer

First you need to get rid of all newline characters in all your text nodes. Then you can use an identity transform to output your DOM tree. Look at the javadoc for TransformerFactory#newTransformer().

share|improve this answer

Your Answer


