是否有比此代码更优雅的方式将XML文档转换为Java中的字符串? [英] Is there a more elegant way to convert an XML Document to a String in Java than this code?
本文介绍了是否有比此代码更优雅的方式将XML文档转换为Java中的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是当前使用的代码.
public String getStringFromDoc(org.w3c.dom.Document doc) {
try
{
DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
writer.flush();
return writer.toString();
}
catch(TransformerException ex)
{
ex.printStackTrace();
return null;
}
}
推荐答案
依赖 DOM Level3加载/保存:
public String getStringFromDoc(org.w3c.dom.Document doc) {
DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation();
LSSerializer lsSerializer = domImplementation.createLSSerializer();
return lsSerializer.writeToString(doc);
}
这篇关于是否有比此代码更优雅的方式将XML文档转换为Java中的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文