Java 怎么将DOM元素转为字符串

2019年8月11日20:50:37Java 怎么将DOM元素转为字符串已关闭评论 354 804字阅读2分40秒

1.简介

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

2.示例代码

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

 

import java.io.StringWriter;
import javax.xml.transform.OutputKeys;
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;

public class Main {
    public static String domElementToString(org.w3c.dom.Element element) {
        TransformerFactory transFactory = TransformerFactory.newInstance();
        StringWriter buffer = new StringWriter();
        try {
            Transformer transformer = transFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,
                    "yes");
            transformer.transform(new DOMSource(element), new StreamResult(
                    buffer));
        } catch (TransformerException e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }
}

 
继续阅读
编程十万个怎么办