我正在尝试计算文档中有多少元素:
Iterator<?> processDescendants = doc.getDescendants(new ElementFilter("a"));
while(processDescendants.hasNext()) {
numPending++;
}
processDescendants = doc.getDescendants(new ElementFilter("b"));
while(processDescendants.hasNext()) {
numPending++;
}
Run Code Online (Sandbox Code Playgroud)
必须有一种更简单的方法......例如:
processDescendants = doc.getDescendants(new ElementFilter("a|b")); // something like Regex maybe?
Run Code Online (Sandbox Code Playgroud)
有人可以帮忙吗?谢谢.
基本上有两种方法可以做到这一点.简单的方法就是走元素......
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++;
}
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以实现自己的过滤器来添加功能
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;
}
}
Run Code Online (Sandbox Code Playgroud)