Java XML Document Parse parseDocument(InputStream is)

Here you can find the source of parseDocument(InputStream is)

Description

Parses the given input stream as XML and returns the corresponding DOM document.

License

Open Source License

Parameter

Parameter Description
is an input stream

Return

a DOM document if something goes wrong

Declaration

public static Document parseDocument(InputStream is) 

Method Source Code


//package com.java2s;
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;

    /**//from   w w  w  .  j  a v a  2  s . c  o  m
     * Parses the given input stream as XML and returns the corresponding DOM
     * document.
     * 
     * @param is
     *            an input stream
     * @return a DOM document if something goes wrong
     */
    public static Document parseDocument(InputStream is) {
        getImplementation();
        DOMImplementationLS implLS = (DOMImplementationLS) impl;

        // serialize to XML
        LSInput input = implLS.createLSInput();
        input.setByteStream(is);

        // parse without comments and whitespace
        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);
    }

    /**
     * Creates a new instance of the DOM registry and get an implementation of
     * DOM 3 with Load Save objects.
     * 
     */
    private static void getImplementation() {
        if (registry == null) {
            try {
                registry = DOMImplementationRegistry.newInstance();
            } catch (ClassCastException | ClassNotFoundException | InstantiationException
                    | IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        if (impl == null) {
            impl = registry.getDOMImplementation("Core 3.0 XML 3.0 LS");
        }
    }
}

Related

  1. parseDocument(InputStream documentXml)
  2. parseDocument(InputStream in)
  3. parseDocument(InputStream is)
  4. parseDocument(InputStream is)
  5. parseDocument(InputStream is)
  6. parseDocument(Path xmlPath)
  7. parseDocument(Reader reader)
  8. parseDocument(String docText)
  9. parseDocument(String documentString)