Skip to main content

Serializing XML, not printing XML

Posted by iasandcb on June 14, 2006 at 9:49 PM PDT

Suppose you have an org.w3c.dom.Document instance to output, for example, to a web browser screen or just simply on a Console, then hmm... unfortunately, we used to have no standard way within DOM API (used, not now).

Even though we can take advantage of DOM L3 Load/Save from JAXP 1.3, it doesn't mean that everybody is happy with that mainly because JAXP 1.3 is fairly new and you might have no choice but to stick to JAXP 1.2 and earlier.

One fine day, I encountered an outstanding snippet of code:

System.out.println(doc);

where doc is of Document.

And the result? Yes! it works!


...

OK, then can we generalize this? Again unfortunately, in this case Document.toString() method implementation is overriden but Document API doesn't require so. In other words, behaviors of Document.toString() vary from implementation to implementation, so you can't expect it to work always.

Therefore, I'd like to recommend two things:

1. Use the DOM L3 Save feature as long as you can.
If you use JDK 5 and later, you don't have to pay a penny for that. If you need to use JDK 4 and earlier, consider that your system is able to allow you to endorse the new JAXP set.

Here's a short example of how-to.

DOMImplementation implementation= DOMImplementationRegistry.newInstance()
.getDOMImplementation("XML 3.0");
DOMImplementationLS feature = (DOMImplementationLS) implementation.getFeature("LS",
"3.0");
LSSerializer serializer = feature.createLSSerializer();
LSOutput output = feature.createLSOutput();
output.setByteStream(System.out);
serializer.write(doc, output);

2. If your situation is inevitable, choose XMLSerializer in Xerces without depending on Document.toString(). Although it's not a standard approach, it has been working since its inception for many XML guys :-)

Here's also a short example of how-to.

XMLSerializer serializer = new XMLSerializer();
serializer.setOutputByteStream(System.out);
serializer.serialize(doc);

3. I got valuable input from commentators. It's very coincidental that I just recognized that I used the same method as them :-)

TransformerFactory transformerFactory = TransformerFactory
.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty("indent", "yes");
transformer.transform(new DOMSource(node), new StreamResult(System.out));

#1 and #3 uses JAXP API, so if you're concerned about portability of your code, those choices can help you.

Related Topics >>