Java 怎么将DOM解析为XML字符串

2019年7月29日19:36:34Java 怎么将DOM解析为XML字符串已关闭评论 455 882字阅读2分56秒

1.简介

Java 怎么将DOM解析为XML字符串?——请看下文。

2.示例代码

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



import java.io.StringWriter;

import javax.xml.transform.OutputKeys;
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 parseDomToXml(Document xml) {

        try {
            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer xform = factory.newTransformer();

            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,
                    "yes");
            StringWriter writer = new StringWriter();
            transformer.transform(new DOMSource(xml), new StreamResult(
                    writer));
            return writer.getBuffer().toString().replaceAll("\n|\r", "");
        } catch (Exception err) {
            err.printStackTrace();
            return null;
        }
    }
}

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