Java XML Child Get by Name getChildElements(Element parent, String name)

Here you can find the source of getChildElements(Element parent, String name)

Description

Gets the child elements of a parent element.

License

Open Source License

Parameter

Parameter Description
parent the XML parent element
name name of the child elements, if null then all are returned

Declaration

public static List<Element> getChildElements(Element parent, String name) 

Method Source Code

//package com.java2s;
//License from project: GNU General Public License 

import java.util.ArrayList;
import java.util.List;

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

public class Main {
    /**/*from  w w w  . j  a  v  a 2 s .  c o m*/
     * Convenience method for getting all child elements.
     * 
     * @see #getChildElements(Element, String)
     */
    public static List<Element> getChildElements(Element parent) {
        return getChildElements(parent, null);
    }

    /**
     * Gets the child elements of a parent element. Unlike DOM's getElementsByTagName, this does no recursion,
     * uses local name (namespace free) instead of tag name, result is a proper Java data structure and result
     * needs no casting. In other words, this method does not suck unlike DOM.
     * 
     * @param parent the XML parent element
     * @param name name of the child elements, if null then all are returned
     */
    public static List<Element> getChildElements(Element parent, String name) {
        List<Element> childElements = new ArrayList<Element>();
        NodeList childNodes = parent.getChildNodes();

        for (int i = 0; i < childNodes.getLength(); i++) {
            // get elements
            if (childNodes.item(i).getNodeType() == Node.ELEMENT_NODE) {

                // match element name
                Element childElement = (Element) childNodes.item(i);
                if (name == null || childElement.getLocalName().equals(name)) {
                    childElements.add(childElement);
                }
            }
        }

        return childElements;
    }
}

Related

  1. getChildElements(Element element, String tagName)
  2. getChildElements(Element p_rootElement, String p_elementName)
  3. getChildElements(Element parent, String elementTag)
  4. getChildElements(Element parent, String localName)
  5. getChildElements(Element parent, String name)
  6. getChildElements(Element parent, String name)
  7. getChildElements(Element parent, String nsUri, String localPart)
  8. getChildElements(Element parent, String nsUri, String localPart)
  9. getChildElements(Element parent, String tagName)