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 {
    /**
     * Method provides getting Element objects out of a NodeList. This method is
     * useful if the xml file is formated with whitespaces because they are
     * interpreted by the DOM parser as text nodes. So especially calls to<br>
     * getFirstChild(), getLastChild(), etc<br>
     * will not surely return elements. To be sure, that you will get an Element
     * use this method by giving the list of child nodes
     * (parent.getChildNodes()) and the parent node (necessary so that only the
     * direct child will be returned and no deeper ones).<br>
     * If no Element is in the list that is a direct child of parent null will
     * be returned.
     * 
     * @param childs
     *            a NodeList that contains all nodes which should be checked
     *            wether they are elements and direct childs of the given
     *            parent. The first node that matches these criterions will be
     *            returned
     * @param parent
     *            the parent node of the given child nodes
     * 
     * @return the first Element of the given NodeList whose parent node is the
     *         given parent. If no such Element exists null will be returned
     */
    public static Element getChildElement(NodeList childs, Node parent) {
        Node childNode;
        String parentName;

        parentName = parent.getNodeName();

        for (int i = 0; i < childs.getLength(); i++) {
            childNode = childs.item(i);

            if ((childNode instanceof Element) && (childNode.getParentNode().getNodeName().equals(parentName))) {
                return (Element) childNode;
            }
        }

        return null;
    }
}