Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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.Element;

import org.w3c.dom.NodeList;

public class Main {
    private static final Map<String, XPathExpression> COMPILED_EXPRESSION_CACHE = new HashMap<String, XPathExpression>();
    private static final XPath XPATH = XPathFactory.newInstance().newXPath();

    /**
     * Checks in under a given root element whether it can find a child elements
     * which match the XPath expression supplied. Returns a {@link List} of
     * {@link Element} if they exist. Please note that the XPath parser used is
     * NOT namespace aware. So if you want to find a element <beans><sec:http>
     * you need to use the following XPath expression '/beans/http'.
     * 
     * @param xPathExpression the xPathExpression
     * @param root the parent DOM element
     * @return a {@link List} of type {@link Element} if discovered, otherwise
     *         an empty list (never null)
     */
    public static List<Element> findElements(final String xPathExpression, final Element root) {
        final List<Element> elements = new ArrayList<Element>();
        NodeList nodes = null;

        try {
            XPathExpression expr = COMPILED_EXPRESSION_CACHE.get(xPathExpression);
            if (expr == null) {
                expr = XPATH.compile(xPathExpression);
                COMPILED_EXPRESSION_CACHE.put(xPathExpression, expr);
            }
            nodes = (NodeList) expr.evaluate(root, XPathConstants.NODESET);
        } catch (final XPathExpressionException e) {
            throw new IllegalArgumentException("Unable evaluate xpath expression", e);
        }

        for (int i = 0, n = nodes.getLength(); i < n; i++) {
            elements.add((Element) nodes.item(i));
        }
        return elements;
    }
}