Arvind
Arvind

Reputation: 6474

dom4j-java- how to get all elements (parent or children) within root that have specific element name

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

Answers (3)

Ankit Singh
Ankit Singh

Reputation: 11

This regex worked for me:

document.selectNodes(".//*")

Upvotes: 1

Viktor Zhurbenko
Viktor Zhurbenko

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

Alex
Alex

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

Related Questions