Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/**
 * Copyright (C) 2010 http://flowas.net/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * You can write to flowas@gmial.com for more customer requirement.
 */

import java.util.ArrayList;

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

import org.w3c.dom.NodeList;

public class Main {
    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 null
     */
    public static List<Element> findElements(String xPathExpression, Element root) {
        List<Element> elements = new ArrayList<Element>();
        NodeList nodes = null;

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

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