How to serialize DOM in Java

Given a DOM Node

Node node ...

the following two ways can be used to serialize the Node into a String.

1. DOM3

DOMImplementationRegistry registry =
     DOMImplementationRegistry.newInstance();
DOMImplementationLS impl =
    (DOMImplementationLS) registry.getDOMImplementation("LS");
LSSerializer lsSerializer = impl.createLSSerializer();
String s = lsSerializer.writeToString(Node node);


2. JAXP

TransformerFactory tf = TransformerFactory.newInstance();
Transformer serializer = tf.newTransformer();
StringWriter sw = new StringWriter();
serializer.transform(new DOMSource(node), new StreamResult(sw));
String s = sw.getBuffer().toString();


In order to create XMLContent RDF, you may have to do two separate 
serialization steps for the nodes to go into xmlLeadingMisc and xmlRest 
depending on whether there is a document type declaration.


I'll send another mail about the reparsing process.
-- 
Johannes Koch
BIKA Web Compliance Center - Fraunhofer FIT
Schloss Birlinghoven, D-53757 Sankt Augustin, Germany
Phone: +49-2241-142628    Fax: +49-2241-142065

Received on Wednesday, 5 March 2008 16:25:53 UTC