我必须递归地搜索 DOM 结构中的特定元素,但现在我完全“卡住”了,无法找到我的算法错误的地方。
Alg 搜索元素表,如果存在则必须返回 true。
private boolean isCompositeExists(Node fieldNode) {
NodeList childNodes = fieldNode.getChildNodes();
if (childNodes != null) {
for (int i = 0; i < childNodes.getLength(); i++) {
Node child = childNodes.item(i);
isCompositeExists(child);
if (child.getNodeName().equals("table")) {
return true;
}
}
}
return false;
}
最佳答案
您可能需要类似的东西:
private boolean isCompositeExists(Node fieldNode) {
NodeList childNodes = fieldNode.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node child = childNodes.item(i);
if (child.getNodeName().equals("table") || isCompositeExists(child)) {
return true;
}
}
return false;
}
请注意,您不需要检查 getChildNodes()
是否为 null
。
关于java DOM 对象的递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21701989/