Java tutorial
//package com.java2s; import org.w3c.dom.Element; import org.w3c.dom.Node; public class Main { /** * Returns the first direct child of the given element whose name matches {@code tag}. * <p> * Example: let the {@link Element} {@code root} correspond to: * * <pre> * {@code <root> * <name> * <first>John</first> * <last>Smith</last> * </name> * <last>BlahBlah</last> * </root> * * getFirstDirectChild(root, "last"); // returns the element corresponding to <last>BlahBlah</last>} * </pre> * * @param parent * The {@link Element} to get the child from. * @param tag * The element name of the child to look for. * @return The {@link Element} corresponding to the child if any was found, {@code null} * otherwise. */ public static Element getFirstDirectChild(Element parent, String tag) { for (Node child = parent.getFirstChild(); child != null; child = child.getNextSibling()) { if (child instanceof Element && tag.equals(child.getNodeName())) { return (Element) child; } } return null; } }