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.List;

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

public class Main {
    /**
     * @param element
     * @return all child elements of the specified node.
     */
    public static List<Element> getChildElements(Node element) {
        List<Element> childElems = new ArrayList<Element>();

        for (Node node = element.getFirstChild(); node != null; node = node.getNextSibling()) {
            if (node instanceof Element) {
                childElems.add((Element) node);
            }
        }

        return childElems;
    }

    /**
     * Returns all child elements of the specified node with the specified name.
     * @param element
     * @param elementName
     * @return the list of child elements
     */
    public static List<Element> getChildElements(Node element, String elementName) {
        List<Element> childElems = new ArrayList<Element>();

        for (Node node = element.getFirstChild(); node != null; node = node.getNextSibling()) {
            if (node instanceof Element) {
                Element childElem = (Element) node;
                String elemName = getElementName(childElem);

                if (elementName.equals(elemName))
                    childElems.add(childElem);
            }
        }

        return childElems;
    }

    /**
     * Returns the element name of the given element.
     * @param element
     * @return String
     */
    public static String getElementName(Element element) {
        // When loading from disk the local name will be setup correctly, but if the local name
        // is fetched directly after calling Document.createElement() then the value will be null.
        // See the JavaDoc for more info.  To workaround this, use the complete node name.
        String elemName = element.getLocalName();
        if (elemName == null) {
            elemName = element.getNodeName();
        }
        return elemName;
    }
}