Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Open Source License 

import java.io.File;
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.w3c.dom.Document;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class Main {
    public static Document parseXmlDocument(String xml, boolean namespaceAware)
            throws ParserConfigurationException, SAXException, IOException {
        DocumentBuilder docBuilder = buildDocumentBuilder(namespaceAware);
        Document doc = docBuilder.parse(new InputSource(new StringReader(xml)));

        // normalize text representation
        doc.getDocumentElement().normalize();

        return doc;
    }

    public static Document parseXmlDocument(File file, boolean namespaceAware)
            throws ParserConfigurationException, SAXException, IOException {
        DocumentBuilder docBuilder = buildDocumentBuilder(namespaceAware);
        Document doc = docBuilder.parse(file);

        // normalize text representation
        doc.getDocumentElement().normalize();

        return doc;
    }

    public static Document parseXmlDocument(InputStream is, boolean namespaceAware)
            throws ParserConfigurationException, SAXException, IOException {
        DocumentBuilder docBuilder = buildDocumentBuilder(namespaceAware);
        Document doc = docBuilder.parse(is);

        // normalize text representation
        doc.getDocumentElement().normalize();

        return doc;
    }

    private static DocumentBuilder buildDocumentBuilder(boolean namespaceAware)
            throws ParserConfigurationException {
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        docBuilderFactory.setNamespaceAware(namespaceAware);
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        return docBuilder;
    }
}