Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

public class Main {
    /**
     * Select only one node what matches given xpath query
     *
     * @param doc        xml document
     * @param expression xpath query
     * @return first element which confirms given xpath query.
     * @throws XPathExpressionException in case of any errors.
     */
    public static Element queryElement(final Document doc, final String expression)
            throws XPathExpressionException {
        final XPath xpath = XPathFactory.newInstance().newXPath();
        return (Element) xpath.evaluate(expression, doc, XPathConstants.NODE);
    }

    /**
     * Select only one node what matches given xpath query
     *
     * @param node       xml node
     * @param expression xpath query
     * @return first element which confirms given xpath query.
     * @throws XPathExpressionException in case of any errors.
     */
    public static Element queryElement(final Node node, final String expression) throws XPathExpressionException {
        final XPath xpath = XPathFactory.newInstance().newXPath();
        return (Element) xpath.evaluate(expression, node, XPathConstants.NODE);
    }
}