Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.util.ArrayList;

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

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class Main {

    public static ArrayList<Element> getChildrenByTag(Element el, String tag) {
        return getElementByXPath(el, tag);
    }

    public static ArrayList<Element> getElementByXPath(Element el, String name) {
        try {
            NodeList nl = (NodeList) XPathFactory.newInstance().newXPath().evaluate(name, el,
                    XPathConstants.NODESET);
            return nodelistToElement(nl);
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static ArrayList<Element> nodelistToElement(NodeList nl) {
        ArrayList<Element> ret = new ArrayList<Element>();
        for (int i = 0; i < nl.getLength(); i++) {
            if (nl.item(i) instanceof Element)
                ret.add((Element) nl.item(i));
        }
        return ret;
    }
}