Java 怎么将DOM树转换为字符串

2019年7月29日19:35:23Java 怎么将DOM树转换为字符串已关闭评论 421 568字阅读1分53秒

1.简介

Java 怎么将DOM树转换为字符串?——请看下文。

2.示例代码

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


import java.io.
     
    public static String domToString(Document domDoc)
            throws TransformerException, TransformerConfigurationException {
        TransformerFactory transFact = TransformerFactory.newInstance();
        Transformer trans = transFact.newTransformer();
        trans.setOutputProperty(OutputKeys.INDENT, "yes");
        StringWriter sw = new StringWriter();
        Result result = new StreamResult(sw);

        try {
            trans.transform(new DOMSource(domDoc), result);
        } catch (TransformerException te) {
            System.out.println(te.getMessageAndLocation());
            throw te;
        }
        return sw.toString();
    }
}

 
编程十万个怎么办