Java 怎么从文档(Document)获取XML内容字符串

2019年7月29日19:13:03Java 怎么从文档(Document)获取XML内容字符串已关闭评论 751 630字阅读2分6秒

1.简介

Java 怎么从文档(Document)获取XML内容字符串?——请看下文。

2.示例代码

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


import java.io.StringWriter;

import org.w3c.dom.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;

public class Main {
    public static String getXMLContent(Document d) {
        String result = "";
        try {
            TransformerFactory tff = TransformerFactory.newInstance();
            Transformer tf = tff.newTransformer();
            tf.setOutputProperty(OutputKeys.INDENT, "yes");
            StringWriter sw = new StringWriter();
            StreamResult sr = new StreamResult(sw);
            DOMSource source = new DOMSource(d);
            tf.transform(source, sr);
            result = sw.toString();
        } catch (Exception ex) {
            result = "";
        }
        return result;
    }
}

 
编程十万个怎么办