Java XPath Find query(Node context, String query)

Here you can find the source of query(Node context, String query)

Description

Performs a xpath query on a document and returns the matching nodelist.

License

Open Source License

Parameter

Parameter Description
context the Context where to start with the query
query the XPath-Query

Exception

Parameter Description
Exception on error

Return

nodelist of matches

Declaration

public static NodeList query(Node context, String query) throws Exception 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

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.Node;
import org.w3c.dom.NodeList;

public class Main {
    /**/*  w  w w  .ja v  a 2s . c  om*/
     * Performs a xpath query on a document and returns the matching nodelist.
     *
     * @param doc
     * @param xpathQuery
     * @return nodelist of matches
     * @throws Exception
     */
    public static NodeList query(Document doc, String xpathQuery) throws Exception {
        NodeList result = null;
        // prepare XPath
        XPath xpath = XPathFactory.newInstance().newXPath();

        try {
            // query xml
            result = (NodeList) xpath.evaluate(xpathQuery, doc, XPathConstants.NODESET);
        } catch (XPathExpressionException xpx) {
            throw new Exception("Error evaluating XPath: " + xpx.getMessage(), xpx);
        }
        return result;
    }

    /**
     * Performs a xpath query on a document and returns the matching nodelist.
     *
     * @param context the Context where to start with the query
     * @param query the XPath-Query
     * @return nodelist of matches
     * @throws Exception on error
     */
    public static NodeList query(Node context, String query) throws Exception {
        NodeList result = null;
        XPath xpath = XPathFactory.newInstance().newXPath();

        try {
            result = (NodeList) xpath.evaluate(query, context, XPathConstants.NODESET);
        } catch (XPathExpressionException xpx) {
            throw new Exception("Error evaluating XPath: " + xpx.getMessage(), xpx);
        }
        return result;
    }
}

Related

  1. findNodeByXPath(Node base, String xpath)
  2. findNodeByXpath(String xpathExpression, String fileName)
  3. findNodeByXPath(String xPathString, Object source)
  4. findNodes(final Node node, final String expression)
  5. findNodesByXPath(Node contextNode, String expression)
  6. querySingle(Node node, String xpathQuery, final String filePath)