Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import org.w3c.dom.*;

import javax.xml.xpath.*;

public class Main {
    public static Document doc = null;

    private static Node getSingleNodeElementByXpath(String xpath) throws Exception {
        NodeList list = getNodeListByXpath(xpath);
        Node node = null;
        if (list.getLength() > 0 && list.item(0).getNodeType() == Node.ELEMENT_NODE) {
            node = list.item(0);
        } else {
            throw new Exception("Xpath Query did not result in a Node element. Check your Xpath expression");
        }
        return node;
    }

    private static NodeList getNodeListByXpath(String xpath) throws Exception {
        XPath xPath = XPathFactory.newInstance().newXPath();
        String expression = xpath;

        NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(doc, XPathConstants.NODESET);
        return nodeList;
    }
}