Search code examples
javadomw3c

W3C DOM API in Java, get child elements by name


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>

Solution

  • getElementsByTagName always operates in the context of element it is called on. If called on Element, only child elements by the given tag name would be accessed. I think you are confusing this with Document object (org.w3c.dom.Document) getElementsByTagName method, then all elements by the given tag name in the document will be returned.