Java 怎么将文档(Document)转换为字符串

2019年7月29日20:47:02Java 怎么将文档(Document)转换为字符串已关闭评论 855 702字阅读2分20秒

1.简介

Java 怎么将文档(Document)转换为字符串?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */


import java.io.StringWriter;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;

public class Main {
    public static String transformToString(Document doc) {
        DOMSource domSource = new DOMSource(doc);
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer;
        try {
            transformer = tf.newTransformer();
            transformer.transform(domSource, result);
        } catch (Exception e) {
            
            e.printStackTrace();
        }
        return writer.toString();
    }
}

 
编程十万个怎么办