Printing XML
Printing XML
A question came up at the end of last week from a colleague "In Java how do I convert a DOM document object into a string?"So the basic problem is that 'toString' on an 'org.w3c.dom.Element or 'org.w3c.dom.Document' does not, as you might expect, return a string representation of an XML document, but rather returns the object identifier. A closer look reveals that there seems to be no other function on Document or Element to convert the DOM (Document Object Model) to a String.
So here is an answer.
First of all create an empty org.w3c.dom.XMLTransform.
javax.xml.transform.TransformerFactory tfactory = TransformerFactory.newInstance();
javax.xml.transform.Transformer xform = tfactory.newTransformer();
Then wrap the DOM into a javax.xml.transform.Source.javax.xml.transform.Transformer xform = tfactory.newTransformer();
javax.xml.transform.Source src = new DOMSource(doc);
Now create a java.io.StringWriter to receive the output and wrap it into a javax.xml.transform.stream.StreamResult.java.io.StringWriter writer = new StringWriter();
Result javax.xml.transform.result = new javax.xml.transform.stream.StreamResult(writer);
Finally use your empty transform to read from the source (your XML document in DOM format), apply a transform (a do nothing transform) and write the result (to your StreamResult which in turn is based on a StringWriter).Result javax.xml.transform.result = new javax.xml.transform.stream.StreamResult(writer);
xform.transform(src, result);
We can now extract the DOM as a text string by using the toString method on the StringWriter that we created.System.out.println(writer.toString());
Note that this works for both whole documents and also individual sub-trees (document fragments) within the document.All this leaves you wondering why Element does not have an generateXmlAsString() method...