Java XPath Find findNodes(final Node node, final String expression)

Here you can find the source of findNodes(final Node node, final String expression)

Description

find Nodes

License

Open Source License

Declaration

public static List<Node> findNodes(final Node node,
            final String expression) throws XPathExpressionException 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2013, 2014 IBH SYSTEMS GmbH and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:/*w ww  .  j a  v  a 2 s.  c  o  m*/
 *     IBH SYSTEMS GmbH - initial API and implementation
 *     IBH SYSTEMS GmbH - add getText method
 *******************************************************************************/

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
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 XPathFactory xpf = XPathFactory.newInstance();

    public static List<Node> findNodes(final Node node,
            final String expression) throws XPathExpressionException {
        final XPath path = xpf.newXPath();
        final XPathExpression expr = path.compile(expression);
        final NodeList nodeList = (NodeList) expr.evaluate(node,
                XPathConstants.NODESET);

        if (nodeList == null) {
            return Collections.emptyList();
        }

        final List<Node> result = new LinkedList<Node>();
        for (int i = 0; i < nodeList.getLength(); i++) {
            result.add(nodeList.item(i));
        }

        return result;
    }
}

Related

  1. findAll(Node root, String xPath)
  2. findNode(String xPathExpression, Element root)
  3. findNodeByXPath(Node base, String xpath)
  4. findNodeByXpath(String xpathExpression, String fileName)
  5. findNodeByXPath(String xPathString, Object source)
  6. findNodesByXPath(Node contextNode, String expression)
  7. query(Node context, String query)
  8. querySingle(Node node, String xpathQuery, final String filePath)