tags:

views:

435

answers:

3

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>
+1  A: 

Not all elements in the document — all descendant elements of the element it's called on. It sounds like that's what you want. You just need to be calling it on the right Element. See here.

Syntactic
+1  A: 

getElementByTagName 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) getElementByTagName method, then all elements by the given tag name in the document will be returned.

Fazal
A: 

I had a similar problem. Try to look at the Node class instead:

http://java.sun.com/javase/6/docs/api/org/w3c/dom/Node.html#getChildNodes()

There is a method called "getChildNodes" which returns the list of all direct child nodes. You then need to filter that list to only get the element-nodes with the right tagname.

Jesper Andersen