Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LSSerializer vs Transformer for serializing xml to String

Tags:

java

dom

xml

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();
}
like image 853
John Fitzpatrick Avatar asked Nov 30 '11 09:11

John Fitzpatrick


1 Answers

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:
    • Is there a more elegant way to convert an XML Document to a String in Java than this code?
    • https://stackoverflow.com/questions/1137488/ways-of-producing-xml-in-java
like image 122
OmegaZiv Avatar answered Oct 12 '22 23:10

OmegaZiv