Java 怎么使用Transformer从节点获取XML字符串

2019年7月22日22:37:25Java 怎么使用Transformer从节点获取XML字符串已关闭评论 481 854字阅读2分50秒

1.简介

Java 怎么使用Transformer从节点获取XML字符串?——请看下文。

2.示例代码

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


import java.io.StringWriter;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Node;

public class Main {

    public static String getXMLString(Node doc)
            throws TransformerException, TransformerConfigurationException {
        TransformerFactory tranFactory = TransformerFactory.newInstance();
        Transformer aTransformer = tranFactory.newTransformer();

        StringWriter sw = new StringWriter();

        Source src = new DOMSource(doc);
        Result dest = new StreamResult(sw);

        aTransformer.transform(src, dest);

        return sw.toString();
    }
}

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