我正在尝试计算文档中有多少个特定元素:
Iterator<?> processDescendants = doc.getDescendants(new ElementFilter("a"));
while(processDescendants.hasNext()) {
numPending++;
}
processDescendants = doc.getDescendants(new ElementFilter("b"));
while(processDescendants.hasNext()) {
numPending++;
} 一定有更简单的方法...例如:
processDescendants = doc.getDescendants(new ElementFilter("a|b")); // something like Regex maybe?有人能帮上忙吗?谢谢。
发布于 2012-02-07 23:32:09
基本上有两种方法可以做到这一点。最简单的方法就是在元素中漫步。
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++;
}
}或者,您可以实现自己的筛选器来添加功能
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;
}
}发布于 2012-02-07 23:20:26
我不这么认为,但是您可以为JDOM解析器实现自己的匹配,比如MatchABElementFilter,并使 Filter ()方法为名称为"a“或"b”的元素类型的对象返回"true“。
发布于 2012-02-07 23:50:33
有一种声明式的方法来做你想做的事情。它的XPath表达式是//a | //b。
JDOM包含a utility class for making XPath queries,您可以返回匹配节点的列表,并可以调用列表上的size来获取计数。
https://stackoverflow.com/questions/9178396
复制相似问题