Java XML Parse Stream parse(InputStream is)

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

Description

Parses an input stream of xml data into a DOM tree

License

Open Source License

Parameter

Parameter Description
is a parameter

Return

the DOM tree

Declaration

public static Document parse(InputStream is) 

Method Source Code

//package com.java2s;
/**//from  w  w  w.j  a v a2  s. c  om
 * Copyright (c) {2003,2011} {openmobster@gmail.com} {individual contributors as indicated by the @authors tag}.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 */

import java.io.InputStream;
import java.io.ByteArrayInputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;

public class Main {
    private static DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    /**
     * Parses an input stream of xml data into a DOM tree
     * 
     * @param is
     * @return the DOM tree
     */
    public static Document parse(InputStream is) {
        try {
            Document document = null;

            DocumentBuilder builder = factory.newDocumentBuilder();
            document = builder.parse(is);

            return document;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    /**
     * Parses a String of xml data into a DOM tree
     * 
     * @param xml
     * @return the DOM tree
     */
    public static Document parse(String xml) {
        InputStream is = null;
        try {
            Document document = null;

            DocumentBuilder builder = factory.newDocumentBuilder();
            is = new ByteArrayInputStream(xml.getBytes());
            document = builder.parse(is);

            return document;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}

Related

  1. parse(InputStream is)
  2. parse(InputStream is)
  3. parse(InputStream is)
  4. parse(InputStream is)
  5. parse(InputStream is)
  6. parse(InputStream s, boolean validateIfSchema)
  7. parse(InputStream stream)
  8. parse(XMLStreamReader reader)
  9. parse(XMLStreamReader reader, String... elementNames)