W3C DOM API in Java, get child elements by name

benstpierre picture benstpierre · Apr 14, 2010 · Viewed 52.2k times · Source

I just realized that the method Element.getElementsByTagName("someTagName") returns a nodelist of all elements in the document that have a given tagname. What if I just want to get all child elements by tag name?

For example...

<person>
  <name>Bob</name>
  <car>
    <name>Toyota Corolla</name>
  </car>
</person>

Answer

Eng.Fouad picture Eng.Fouad · Oct 16, 2012
public static Element getDirectChild(Element parent, String name)
{
    for(Node child = parent.getFirstChild(); child != null; child = child.getNextSibling())
    {
        if(child instanceof Element && name.equals(child.getNodeName())) return (Element) child;
    }
    return null;
}