Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

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

public class Main {
    /**
     * Get first child element with the provided node name and attribute that
     * are direct child the provided element.
     * 
     * @param parent
     * @param name
     * @param attributeName
     * @param attributeValue
     * @return element if found, otherwise null
     */
    public static Element getChildElementByNameAndAttribute(Element parent, String name, String attributeName,
            String attributeValue) {
        assertNotNull(parent);

        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)) {
                Element element = (Element) node;
                if (element.getAttribute(attributeName).equals(attributeValue)) {
                    return element;
                }
            }
        }

        return null;
    }

    /**
     * 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");
        }
    }
}