Java XML Parse Stream parseXml(InputStream in)

Here you can find the source of parseXml(InputStream in)

Description

parse Xml

License

Apache License

Declaration

public static Document parseXml(InputStream in) throws IOException, SAXException, ParserConfigurationException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.EntityResolver;
import org.w3c.dom.Document;

public class Main {
    public static Document parseXml(InputStream in) throws IOException, SAXException, ParserConfigurationException {
        DocumentBuilder builder = getBuilder();
        InputStream bin = new BufferedInputStream(in);
        Document ret = builder.parse(new InputSource(bin));
        return ret;
    }//from ww w . j av  a 2  s.com

    public static Document parseXml(String s) throws IOException, SAXException, ParserConfigurationException {
        DocumentBuilder builder = getBuilder();
        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(s));
        Document ret = builder.parse(is);
        return ret;
    }

    private static DocumentBuilder getBuilder() throws ParserConfigurationException {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
        factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

        DocumentBuilder builder = factory.newDocumentBuilder();
        // prevent DTD entities from being resolved.
        builder.setEntityResolver(new EntityResolver() {
            @Override
            public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
                return new InputSource(new StringReader(""));
            }
        });

        return builder;
    }
}

Related

  1. parser(InputStream inputStream)
  2. parseStream(InputStream stream, boolean validate, boolean expandEntityRefs)
  3. parseStreamToXML(InputStream in)
  4. parseText(XMLStreamReader parser)
  5. parseValue(XMLStreamReader xmlRdr, String elementName)
  6. parseXml(InputStream in)
  7. parseXML(InputStream in)
  8. parseXml(InputStream inputStream, boolean validating)
  9. parseXML(InputStream is)