Java 怎么将给定的输入流(InputStream)解析为XML并返回相应的DOM文档(Document)

2019年7月28日22:02:28Java 怎么将给定的输入流(InputStream)解析为XML并返回相应的DOM文档(Document)已关闭评论 473 1520字阅读5分4秒

1.简介

Java 怎么将给定的输入流(InputStream)解析为XML并返回相应的DOM文档(Document)?——请看下文。

2.示例代码

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

 

import java.io.ByteArrayInputStream;

import java.io.InputStream;

import org.w3c.dom.DOMConfiguration;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;

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

import org.w3c.dom.ls.LSParser;

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

    
    public static Document parseDocument(InputStream is) {
        getImplementation();
        DOMImplementationLS implLS = (DOMImplementationLS) impl;

        
        LSInput input = implLS.createLSInput();
        input.setByteStream(is);

        
        LSParser builder = implLS.createLSParser(
                DOMImplementationLS.MODE_SYNCHRONOUS, null);
        DOMConfiguration config = builder.getDomConfig();
        config.setParameter("comments", false);
        config.setParameter("element-content-whitespace", false);

        return builder.parse(input);
    }

    
    public static Document parseDocument(String str) {
        return parseDocument(new ByteArrayInputStream(str.getBytes()));
    }

    
    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);
        }
    }
}

 
继续阅读