Java XML Child Node Get getChildElements(Node element)

Here you can find the source of getChildElements(Node element)

Description

get Child Elements

License

Open Source License

Parameter

Parameter Description
element a parameter

Return

all child elements of the specified node.

Declaration

public static List<Element> getChildElements(Node element) 

Method Source Code

//package com.java2s;

import java.util.ArrayList;

import java.util.List;

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

public class Main {
    /**/*from w  w  w.j  av  a2  s.  c om*/
     * @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;
    }
}

Related

  1. getChildElements(final Node node)
  2. getChildElements(final Node parentNode, final String... childNodeNames)
  3. getChildElements(Node node)
  4. getChildElements(Node node)
  5. getChildElements(Node node)
  6. getChildElements(Node node)