有没有更加优雅的方式将XML文档转换为Java中的字符串比这个代码?

前端之家收集整理的这篇文章主要介绍了有没有更加优雅的方式将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 Load/Save
public String getStringFromDoc(org.w3c.dom.Document doc)    {
    DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation();
    LSSerializer lsSerializer = domImplementation.createLSSerializer();
    return lsSerializer.writeToString(doc);   
}

猜你在找的XML相关文章