Execute an xpath query on a specific node. - Java XML

Java examples for XML:XPath

Description

Execute an xpath query on a specific node.

Demo Code


//package com.java2s;

import javax.xml.namespace.QName;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Node;

public class Main {
    /**/* ww  w .j a v  a 2 s  .co m*/
     * Execute an xpath query on a specific node.
     *
     * The type parameter specifies the expected type of the result of the
     * query. Typical types are:
     *
     *  XPathContants.NUMBER: A java Double that corresponds to a numeric
     *  literal in the XML document
     *  XPathConstants.STRING: A java String that corresponds to a text literal
     *  in the XML document
     *  XPathConstants.NODESET: A NodeList that contains a list of nodes
     *  in the XML document
     *  XPathConstants.NODE: A particular Node inside the XML document
     *
     * @param doc The node on which the xpath expression is to be executed
     * @param xpath_expr The XPath expression to be executed
     * @param type One of the XPathConstants that specified the expected output.
     * @return The result of the XPath query on the node, of the corresponding
     *         type
     */
    @SuppressWarnings("unchecked")
    public static <T> T xpath(Node doc, String xpath_expr, QName type) {
        XPathFactory xpathfactory = XPathFactory.newInstance();
        XPath xpath = xpathfactory.newXPath();
        XPathExpression expr;
        try {
            expr = xpath.compile(xpath_expr);
            return (T) expr.evaluate(doc, type);
        } catch (XPathExpressionException e) {
            throw new RuntimeException(e);
        }
    }
}

Related Tutorials