Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

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

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