12

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();
}
Draemon
  • 33,955
  • 16
  • 77
  • 104
John Fitzpatrick
  • 4,207
  • 7
  • 48
  • 71
  • have you found an answer by any chance by now? I have wondered the same question myself. – apines Jan 21 '12 at 11:13
  • I didn't get any answers, and couldn't find any articles preferring one or the other. However, nearly all the articles and posts I found on the serializing a String use javax.xml.Transform, so it seems to be the overall preferred approach. In spite of that I went with org.w3c.dom.ls.LSSerializer, and I don't have any solid reason to give for it. I just like the feel of the "One Stop Shopping" I get the by using the org.w3c.dom packages. So far I have nothing negative to report by using this method. So I think my answer is "They both seem ok". – John Fitzpatrick Jan 22 '12 at 20:32

1 Answers1

5

There are several points to consider:

  1. LSSerializer is usually considered faster than Transformer.
  2. Nevertheless it heavily depends on the implementation. A Transformer based on SAX will have good performance. And there are different implementors (Xalan, Xerces, ...).
  3. It is very easy to check which is better in your system. Design a simple test case with a complex XML. Run it in a loop thousdns of time, wrap that with time check (Syste.getCurrentMilliseconds or something) and you've got yourself an answer.
  4. Other nice answers include:
Community
  • 1
  • 1
OmegaZiv
  • 256
  • 2
  • 14
  • Thanks for your illuminating answer. Another issue that concerns me is what I call "Abandonment Likelihood", the likelihood that a creator of a library or API might abandon it, no longer offering updates as the underlying technology (in this case the JDK) changes. Do you think either has a higher likelihood of being abandoned or deprecated? Thanks – John Fitzpatrick Jan 30 '12 at 13:21