Java 怎么将XML DOM作为字符串获取

2019年7月29日19:38:58Java 怎么将XML DOM作为字符串获取已关闭评论 270 1005字阅读3分21秒

1.简介

Java 怎么将XML 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 getStringFromDoc(org.w3c.dom.Document doc) {
        if (doc == null) {
            System.out.println("XML document is null");
        }
        try {
            DOMSource domSource = new DOMSource(doc);
            StringWriter writer = new StringWriter();
            StreamResult result = new StreamResult(writer);
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,
                    "http:
            transformer.transform(domSource, result);
            writer.flush();
            return writer.toString();
        } catch (TransformerException ex) {
            System.out.println("Transformer Exception");
            
            return "Error in transformation";
        }
    }
}

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