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...
Comments (3)
Just to add:
If we are using Oracle XMLParser, a quick way to convert Element to String would be:
//Presuming getXMLPayload() returns XMLElement
XMLElement xmlPayload = getXMLPayload();
java.io.StringWriter writer = new java.io.StringWriter();
xmlPayload.print(writer);
String payloadAsString = writer.toString();
Posted by Amjad | June 19, 2007 7:52 AM
Posted on June 19, 2007 07:52
You can print it from the XMLDocument as well via:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
inputXMLDocument.print( baos );
xml_result_with_cc = baos.toString();
Posted by egivler | June 26, 2007 11:39 AM
Posted on June 26, 2007 11:39
<antony>
All this leaves you wondering why Element does not have an generateXmlAsString() method</antony>
This is a very valid Question. But the answer lies in the Document Object Model. DOM Level 1 and 2 did not define a mechanism for Loading and Saving [serializing] XML documents.
Thus the DOM interfaces like Element, Document etc, that are published W3C java interfaces do not expose APIs to print out / serialize data onto a stream.
But DOM level 3 does expose a "Load and Save" interface that allows loading of XML documents into DOM documents in-memory and vice-versa.
See the DOM Level 3 Load and Save Specification at "http://www.w3.org/TR/DOM-Level-3-LS/"
JDK 1.5 exposes these LS APIs.
See javadoc at http://java.sun.com/j2se/1.5.0/docs/api/org/w3c/dom/ls/package-summary.html
Although LS wasnt supported in DOM 1 and 2, implementations [like Oracle XDK] choose to provide additional APIs to print an XML document into a stream - may it be a print stream, or a string.
See the "print()" methods on oracle.xml.parser.v2.XMLDocument or oracle.xml.parser.v2.XMLElement.
For instance, assume you used a DOMParser to parse an XML into a DOM document.
Here is how you could print it out into a stream.
//read the doc from file into a DOM document
DOMParser parser = new DOMParser();
parser.parse(new FileReader("c:\\temp\\input.xml"));
XMLDocument inputDoc = parser.getDocument();
//print the doc into a string
StringWriter sw = new StringWriter();
inputDoc.print(sw);
System.err.println("XML doc is " + sw.toString());
Note that you need to catch Exceptions in this above snippet. Also ensure you have xmlparserv2.jar in your classpath.
Posted by Ramkumar Menon | August 7, 2007 2:37 PM
Posted on August 7, 2007 14:37