我必须将org.w3c.dom.Document变成java.lang.String。我找到了两种可能的方法,一种使用org.w3c.dom.ls.ls.LSSerializer,另一种使用javax.xml.transform.Transformer。我在下面有各自的样本。
谁能告诉我哪种方法更受青睐?
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();
}
答案 0 :(得分:4)
有几点需要考虑: