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:
Post a Comment