Java XPath Get getNodeList(Node node, String xpath)

Here you can find the source of getNodeList(Node node, String xpath)

Description

Get the W3C NodeList instance associated with the XPath selection supplied.

License

Open Source License

Parameter

Parameter Description
node The document node to be searched.
xpath The XPath String to be used in the selection.

Return

The W3C NodeList instance at the specified location in the document, or null.

Declaration

public static NodeList getNodeList(Node node, String xpath) 

Method Source Code

//package com.java2s;
// License as published by the Free Software Foundation; either

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

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
    private static String ELEMENT_NAME_FUNC = "/name()";
    private static XPathFactory xPathFactory = XPathFactory.newInstance();

    /**// ww w . jav a  2  s. co m
     * Get the W3C NodeList instance associated with the XPath selection
     * supplied.
     * <p/>
     * <b>NOTE</b>: Taken from Milyn Commons.
     *
     * @param node  The document node to be searched.
     * @param xpath The XPath String to be used in the selection.
     * @return The W3C NodeList instance at the specified location in the
     *         document, or null.
     */
    public static NodeList getNodeList(Node node, String xpath) {
        if (node == null) {
            throw new IllegalArgumentException("null 'document' arg in method call.");
        } else if (xpath == null) {
            throw new IllegalArgumentException("null 'xpath' arg in method call.");
        }
        try {
            XPath xpathEvaluater = xPathFactory.newXPath();

            if (xpath.endsWith(ELEMENT_NAME_FUNC)) {
                return (NodeList) xpathEvaluater.evaluate(
                        xpath.substring(0, xpath.length() - ELEMENT_NAME_FUNC.length()), node,
                        XPathConstants.NODESET);
            } else {
                return (NodeList) xpathEvaluater.evaluate(xpath, node, XPathConstants.NODESET);
            }
        } catch (XPathExpressionException e) {
            throw new IllegalArgumentException("bad 'xpath' expression [" + xpath + "].");
        }
    }
}

Related

  1. getNodeList(Element root, String xpath)
  2. getNodeList(File xml, String xpathExpression)
  3. getNodeList(final String expr, final File xmlFile)
  4. getNodeList(InputStream stream, String pattern)
  5. getNodeList(Node node, String path)
  6. getNodeList(Node xmlNode, String xpathString)
  7. getNodeList(Reader reader, String expression)
  8. getNodeListAsArray(Node doc, String xpath)
  9. getNodeListAttValAsStringCol(final String xPath, final Node node, final String attrName)