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 org.w3c.dom.Document;

import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;

public class Main {
    static public NodeList getNodeList(InputStream stream, String pattern)
            throws XPathExpressionException, ParserConfigurationException, SAXException, IOException {
        return getNodeList(getDocument(stream), pattern);
    }

    static public NodeList getNodeList(Document doc, XPath xPath, String pattern) throws XPathExpressionException {
        XPathExpression expr;
        NodeList nl;

        expr = xPath.compile(pattern);
        nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);

        return nl;
    }

    static public NodeList getNodeList(Document doc, String pattern) throws XPathExpressionException {
        XPath xpath = getXPath();
        return getNodeList(doc, xpath, pattern);
    }

    static public Document getDocument(File file) throws IOException, ParserConfigurationException, SAXException {
        InputStream stream = new FileInputStream(file);
        return getDocument(stream);
    }

    static public Document getDocument(Path filePath)
            throws IOException, ParserConfigurationException, SAXException {
        return getDocument(filePath.toFile());
    }

    static public Document getDocument(InputStream stream)
            throws IOException, SAXException, ParserConfigurationException {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();

        Document doc = dBuilder.parse(stream);
        doc.getDocumentElement().normalize();

        return doc;
    }

    static public XPath getXPath() {
        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xpath = xPathfactory.newXPath();

        return xpath;
    }
}