Java tutorial
//package com.java2s; import java.util.LinkedList; import java.util.List; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main { /** * Find all descendant elements with a given name, for a parent element. * @param e * @param name * @return */ public static List<Element> findDescendantsByName(Element e, String name) { List<Element> result = new LinkedList<Element>(); findDescendantsByName(e, name, result); return result; } private static void findDescendantsByName(Element e, String name, List<Element> list) { if (e.getLocalName().equals(name)) list.add(e); for (Element e1 : getChildElements(e)) findDescendantsByName(e1, name, list); } /** * Get all direct child elements of a parent element. * @param e * @return */ public static List<Element> getChildElements(Element e) { return getChildElements(e, null); } /** * Get all direct child elements with a given name, for a parent element. * @param e * @return */ public static List<Element> getChildElements(Element e, String name) { if (e == null) return null; List<Element> result = new LinkedList<Element>(); NodeList list = e.getChildNodes(); for (int i = 0; i < list.getLength(); i++) { Node n = list.item(i); if (n instanceof Element) { if (name == null || name.equals(n.getLocalName()) || n.getLocalName().endsWith(":" + name)) { result.add((Element) n); } } } return result; } }