Wednesday, April 2, 2008

XML Serialization

I have always wondered how to serialize xml to string. Actually in the last years I have implemented this functionality at least twice using different approaches. I think it's time to post the two favorite ways how to do it, just to avoid implementing this functionality once again.

Here is one way:
public static void writeNode(Node node, Writer output) {
DOMImplementation domImpl = node.getOwnerDocument().getImplementation();
DOMImplementationLS domImplLS = (DOMImplementationLS)domImpl.getFeature("LS", "3.0");
LSSerializer serializer = domImplLS.createLSSerializer();
LSOutput serializerOut = domImplLS.createLSOutput();
serializerOut.setCharacterStream(output);
serializer.write(node, serializerOut);
}


Here is another way:
public static void nodeToStream(Node node, OutputStream stream) throws Exception {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.transform(new DOMSource(node), new StreamResult(stream));
}



The second way looks more elegant but it is slower. However, it can be improved by pooling transformers, which will probably make it less elegant.

The second way can be enhanced to produce a pretty xml:
public static String prettyPrintXML(Node node) throws Exception {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty("indent", "yes");
transformer.setOutputProperty(
"{http://xml.apache.org/xslt}indent-amount", "3");
StringWriter output = new StringWriter();
transformer.transform(new DOMSource(node.getOwnerDocument()),
new StreamResult(output));
return output.toString();
}

No comments: