Java XPath Create xPathNodes(String expr, Object context)

Here you can find the source of xPathNodes(String expr, Object context)

Description

x Path Nodes

License

Open Source License

Return

a list of nodes obtained from evaluating an XPath expression

Declaration

public static List<Node> xPathNodes(String expr, Object context) 

Method Source Code

//package com.java2s;
// modify it under the terms of the GNU General Public License

import java.util.ArrayList;

import java.util.List;

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 ThreadLocal<XPath> XPATH_POOL = new ThreadLocal<XPath>() {
        @Override// ww w. j  av a2s . c om
        protected XPath initialValue() {
            return XPathFactory.newInstance().newXPath();
        }
    };

    /**
     * @return a list of nodes obtained from evaluating an XPath expression
     * @since 1.14.1
     */
    public static List<Node> xPathNodes(String expr, Object context) {
        return xPathObjects(expr, context);
    }

    static <T> List<T> xPathObjects(String expr, Object context) {
        try {
            NodeList nodes = (NodeList) xPath().evaluate(expr, context, XPathConstants.NODESET);
            List<T> result = new ArrayList<T>(nodes.getLength());
            for (int i = 0; i < nodes.getLength(); i++)
                result.add((T) nodes.item(i));
            return result;
        } catch (XPathExpressionException e) {
            throw new IllegalArgumentException(e);
        }
    }

    /**
     * @return an XPath object that can be used by the current thread
     * @since 1.14.1
     */
    public static XPath xPath() {
        return XPATH_POOL.get();
    }
}

Related

  1. xpath(String expression)
  2. xpath(String xml, String xpath)
  3. xPath(String xPath)
  4. xpathNode(Node node, String xpath)
  5. xpathNodes(Node node, String expression)
  6. xPathSearch(String input, String expression)