Java 怎么返回给定XML节点的字符串表示形式

2019年8月7日21:01:32Java 怎么返回给定XML节点的字符串表示形式已关闭评论 361 1398字阅读4分39秒

1.简介

Java 怎么返回给定XML节点的字符串表示形式?——请看下文。

2.示例代码

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



import java.io.ByteArrayOutputStream;

import java.io.OutputStream;

import org.w3c.dom.DOMImplementation;

import org.w3c.dom.Node;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;

import org.w3c.dom.ls.LSOutput;

import org.w3c.dom.ls.LSSerializer;

public class Main {
    private static DOMImplementation impl;
    private static DOMImplementationRegistry registry;

    
    public static String writeToString(Node node) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        writeDocument(os, node);
        return os.toString();
    }

    
    public static void writeDocument(OutputStream os, Node node) {
        getImplementation();
        DOMImplementationLS implLS = (DOMImplementationLS) impl;

        
        LSOutput output = implLS.createLSOutput();
        output.setByteStream(os);

        
        LSSerializer serializer = implLS.createLSSerializer();
        serializer.getDomConfig().setParameter("format-pretty-print", true);
        serializer.write(node, output);
    }

    
    private static void getImplementation() {
        try {
            if (registry == null) {
                registry = DOMImplementationRegistry.newInstance();
            }

            if (impl == null) {
                impl = registry.getDOMImplementation("Core 3.0 XML 3.0 LS");
                if (impl == null) {
                    throw new RuntimeException(
                            "no DOM 3 implementation found");
                }
            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("DOM error", e);
        } catch (InstantiationException e) {
            throw new RuntimeException("DOM error", e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException("DOM error", e);
        }
    }
}

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