Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.util.ArrayList;

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

public class Main {
    /**
     * returns the first element with the given tag which attribute "name" equals name string.<br>
     * search only in Element child nodes
     * @param tagName   the tag to search
     * @param name      the "name" attribute value
     * @param searchIn   the element, in which child Nodes will be searched
     * @return   the first element found that matches
     * @throws Exception
     */
    public static Element getChildElementWithName(String tagName, String name, Element searchIn) {
        String attribute = "name";
        ArrayList<Element> list = getChildElementsByTag(tagName, searchIn);
        for (Element e : list) {
            if (name.equals(e.getAttribute(attribute))) {
                return e;
            }
        }
        return null;
    }

    /**
     * get all child elements matching the given tag 
     * 
     * @param tag
     * @param searchIn
     * @return
     */
    public static ArrayList<Element> getChildElementsByTag(String tag, Element searchIn) {
        ArrayList<Element> toReturn = new ArrayList<Element>();
        NodeList list = searchIn.getChildNodes();

        for (int i = 0; i < list.getLength(); i++) {
            Node n = list.item(i);
            if (n instanceof Element && ((Element) n).getTagName().equals(tag)) {
                toReturn.add((Element) n);
            }

        }
        return toReturn;
    }
}