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.Collection;
import java.util.List;

import org.w3c.dom.Element;

import org.w3c.dom.NodeList;

public class Main {
    /**
     * Get a child element with the specified localName. Assumption is that it
     * is in the same namespace as the specified element.
     * 
     * @param element
     * @param localName
     * @return
     */
    public static Element getElement(Element element, String localName) {
        Collection<Element> elements = getElementsByTagName(element, localName);
        if (elements.isEmpty()) {
            return null;
        } else {
            return elements.iterator().next();
        }
    }

    /**
     * Returns all elements under the element with the specified tagname.
     * 
     * @param element
     * @param localName
     * @return
     */
    public static Collection<Element> getElementsByTagName(Element element, String localName) {
        return getDirectChildren(element, localName);
    }

    private static List<Element> getDirectChildren(Element element, String tagName) {
        NodeList nList = element.getElementsByTagName(tagName);
        List<Element> list = new ArrayList<Element>();
        int listLength = nList.getLength();
        for (int i = 0; i < listLength; i++) {
            Element listElement = (Element) nList.item(i);
            if (listElement.getParentNode() == element) {
                list.add(listElement);
            }
        }
        return list;
    }
}