Java – lsserializer vs transformer serializes XML to string

I have to put org w3c. dom. Convert document to Java lang.String. I found two possible ways. One is to use org w3c. dom. ls. Lsserializer, another uses javax xml. transform. Transformer. I have the following sample

Who can tell me which method is the first choice?

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();
}

Solution

There are several points to consider:

>Lsserializer is generally considered to be faster than transformer. > However, it depends largely on implementation The transformer based on Sax will have good performance And there are different implementers (xalan, Xerces,...). > It is very easy to check which is better in the system Design a simple test case with complex XML The time to run it in a loop, including the time check (syste. Getcurrentmilliseconds or something), you have an answer. > Other good 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

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>