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 org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
    /**
     * Get all child elements with the provided name that are direct children
     * the provided element.
     * 
     * @param parent
     *            The parent element
     * @param name
     *            The name of the child elements to find
     * @return The list with child elements, empty list if no matching children
     */
    public static Collection<Element> getChildElementsByName(Element parent, String name) {
        assertNotNull(parent);
        Collection<Element> childList = new ArrayList<Element>();

        NodeList children = parent.getChildNodes();
        Node node;
        for (int i = 0; i < children.getLength(); i++) {
            node = children.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE && node.getNodeName().equals(name)) {
                childList.add((Element) node);
            }
        }

        return childList;
    }

    /**
     * Performs a check that the provided Nodeobject is not null.
     * 
     * @param node
     *            The node to check
     * @throws IllegalArgumentException
     *             In case the node is null
     */
    private static void assertNotNull(Node node) {
        if (node == null) {
            throw new IllegalArgumentException("The input node cannot be null");
        }
    }
}