Java tutorial
//package com.java2s; //License from project: Apache License import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import java.util.ArrayList; import java.util.List; public class Main { /** * Gets the immediately child element from the parent element. * * @param parent * the parent element in the element tree * @param tagName * the specified tag name * @return immediately child element of parent element, NULL otherwise */ public static Element getChildElement(Element parent, String tagName) { List<Element> children = getChildElements(parent, tagName); if (children.isEmpty()) { return null; } else { return children.get(0); } } /** * Gets the immediately child elements list from the parent element. * * @param parent * the parent element in the element tree * @param tagName * the specified tag name * @return the NOT NULL immediately child elements list */ public static List<Element> getChildElements(Element parent, String tagName) { NodeList nodes = parent.getElementsByTagName(tagName); List<Element> elements = new ArrayList<>(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node instanceof Element && node.getParentNode() == parent) { elements.add((Element) node); } } return elements; } }