Java 怎么通过转换器(Transformer)将DOM文档(Document)转换为字符串

2019年7月29日20:49:25Java 怎么通过转换器(Transformer)将DOM文档(Document)转换为字符串已关闭评论 1,134 712字阅读2分22秒

1.简介

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

2.示例代码

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


import java.io.StringWriter;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
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 dom2String(Document d) {
        try {
            TransformerFactory tfactory = TransformerFactory.newInstance();
            Transformer transformer = tfactory.newTransformer();
            StringWriter sw = new StringWriter();
            transformer.transform(new DOMSource(d), new StreamResult(sw));
            return sw.toString();
        } catch (TransformerException e) {
            e.printStackTrace();
        }
        return "";
    }
}

 
编程十万个怎么办