I have to turn a org.w3c.dom.Document into a java.lang.String. I have found two possible approaches, one using org.w3c.dom.ls.LSSerializer and the other using a javax.xml.transform.Transformer. I have samples of each below.
Can anyone tell me which method is to be preferred?
public String docToStringUsingLSSerializer(org.w3c.dom.Document doc) {
DOMImplementationRegistry reg = DOMImplementationRegistry.newInstance();
DOMImplementationLS impl = (DOMImplementationLS) reg.getDOMImplementation("LS");
LSSerializer serializer = impl.createLSSerializer();
return serializer.writeToString(doc);
}
public String docToStringUsingTransformer(org.w3c.dom.Document doc) {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
StringWriter stw = new StringWriter();
transformer.transform(new DOMSource(doc), new StreamResult(stw));
return stw.toString();
}
There are several points to consider:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With