Java 怎么实现节点到字符串的XML转换

2019年7月25日22:34:41Java 怎么实现节点到字符串的XML转换已关闭评论 325 845字阅读2分49秒

1.简介

Java 怎么实现节点到字符串的XML转换?——请看下文。

2.示例代码

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

 


import org.w3c.dom.Node;
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;

import java.io.StringWriter;

public class Main {
    
    public static String nodeToString(final Node node) {
        final StringWriter sw = new StringWriter();
        try {
            final Transformer t = TransformerFactory.newInstance()
                    .newTransformer();
            t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            t.setOutputProperty(OutputKeys.INDENT, "yes");
            t.setOutputProperty(
                    "{http:
            t.transform(new DOMSource(node), new StreamResult(sw));
        } catch (final TransformerException te) {
            System.out.println("nodeToString Transformer Exception");
        }
        return sw.toString();
    }
}

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