2

I'm trying to count how many certain elements the document has:

Iterator<?> processDescendants = doc.getDescendants(new ElementFilter("a")); 

while(processDescendants.hasNext()) {
   numPending++;
}

processDescendants = doc.getDescendants(new ElementFilter("b")); 

while(processDescendants.hasNext()) {
   numPending++;
}   

There has to be an easier way... such as:

processDescendants = doc.getDescendants(new ElementFilter("a|b")); // something like Regex maybe?

Anyone can help? Thank you.

jn1kk
  • 5,012
  • 2
  • 45
  • 72

3 Answers3

6

There are essentially two ways to do it. The easy way is to just walk the elements...

Iterator<?> processDescendants = doc.getDescendants(new ElementFilter()); 

while(processDescendants.hasNext()) {
   Element e =  processDescendants.Next();
   string currentName = e.getTagName();
   if( currentName.equals("a") || currentName.equals("b") )
   {
       numPending++;
   }
}

Or you can implement your own Filter to add the functionality

import org.jdom.filter.Filter;
import org.jdom.Element;

public class ElementRegexFilter implements Filter {

    private String regex = "";

    public ElementRegexFilter( String regex )
    {
        this.regex = regex;
    }

    public boolean matches( Object o )
    {
        if( o instanceof Element )
        {
            String ElementName = ((Element) o).getName();
            return ElementName.matches( regex );
        }
        return false;
    }

}
The Real Baumann
  • 1,941
  • 1
  • 14
  • 20
1

I don't think there is, but you can implement your own Filter for the JDOM parser, something like MatchABElementFilter, and make the match() method return "true" for objects of type element with name "a" or "b"

Shivan Dragon
  • 15,004
  • 9
  • 62
  • 103
1

There is a declarative way to do what you want. The XPath expression for it is //a | //b.

JDOM includes a utility class for making XPath queries, you get back a list of matching nodes and can call size on the list to get your count.

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276