Reputation: 6474
I want to get the number of elements in an xml, which have specific name eg. name="while")
The problem is that if I use the following code- I only get top level elements that have this name--
for ( Iterator i = root.elementIterator( "while" ); i.hasNext(); ) {
Element foo = (Element) i.next();
But any lower level "while" element is not part of the iterator...
What is the most efficient way of obtaining all elements (whether top level or lower level) that have name="while"? Do I have to parse through all elements in document for this purpose?
Upvotes: 1
Views: 11630
Reputation: 1
Element Iterator works only for next level in xPath. To be able to parse all XML and get all Element you have to use some recursion. For example next code will return list of all nodes with "name"
public List<Element> getElementsByName(String name, Element parent, List<Element> elementList)
{
if (elementList == null)
elementList = new ArrayList<Element>();
for ( Iterator i = parent.elementIterator(); i.hasNext(); ) {
Element current = (Element) i.next();
if (current.getName().equalsIgnoreCase(name))
{
elementList.add(current);
}
getElementsByName(name, current, elementList);
}
return elementList;
}
Upvotes: 0
Reputation: 25613
You can use XPath for that using //while
or the name()
function and a wildcard node *
: //*[name() = 'while']
List list = document.selectNodes("//*[name() = 'while']"); // or "//while"
int numberOfNodes = list.size();
for (Iterator iter = list.iterator(); iter.hasNext(); ) {
// do something
}
Upvotes: 1