Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.io.File;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class Main {
    /**
     * Loads the xml file into an xml document and returns the root element.
     * 
     * @param fileName
     *            the fully qualified name of the XML file to load; assumed not
     *            to be <code>null</code>.
     * 
     * @return root element of the xml document, never <code>null</code>.
     * 
     * @throws Exception
     *             on any error
     */
    public static Element loadXmlResource(final String fileName) throws Exception {
        File file = new File(fileName);
        DocumentBuilder db = getDocumentBuilder();
        Document doc = db.parse(file);
        return doc.getDocumentElement();
    }

    /**
     * Loads the imput stream and returns the root element.
     * 
     * @param in
     *            Input Stream.
     * 
     * @return root element of the xml document, never <code>null</code>.
     * 
     * @throws Exception
     *             on any error
     */
    public static Element loadXmlResource(final InputStream in) throws Exception {
        DocumentBuilder db = getDocumentBuilder();
        Document doc = db.parse(in);
        return doc.getDocumentElement();
    }

    /**
     * Returns a <code>DocumentBuilder</code>, which is used for parsing XML
     * documents.
     * 
     * @return a <code>DocumentBuilder</code> which is used for parsing XML
     *         documents. Never <code>null</code>.
     */
    public static DocumentBuilder getDocumentBuilder() {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(true);
            dbf.setValidating(false);

            return dbf.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }
}