java DOM 对象的递归

标签 java xml recursion

我必须递归地搜索 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/

相关文章:

go - 递归内部函数 Golang

java - com.amazonaws.services.s3.model.AmazonS3Exception : Forbidden (Service: Amazon S3; Status Code: 403; Error Code: 403 Forbidden; Request ID: XXXXXXXX)

python - 从 Python 中的特定 XML 节点检索注释

loops - 在 Clojure 中退出循环

c - 寻找一组字符

java - 警告 : No mapping found for HTTP request with URI[] in DispatcherServlet with name []

java - 在 STS Gradle 中禁用打印 stracktrace/BuildException 输出

java - vector : How do I check each element to see if it equals a user input?

c# - 如何从给定的字符串中获取整数值?

java - 发布已存在的 jar 文件