简体   繁体   English

使用递归在java中查找XML文件中特定标记的出现位置

[英]Find occurrences of a specific tag in an XML file in java using recursion

I need to return the number of occurrences of the given tag, for example, a user will provide a link to an xml file and the name of the tag to find and it will return the number of occurrences of that specific tag. 我需要返回给定标记的出现次数,例如,用户将提供指向xml文件的链接以及要查找的标记的名称,它将返回该特定标记的出现次数。 My code so far only works for the child of the parent node, whereas I need to check all the child of the child nodes as well, and I quite don't understand how to iterate through all of the elements of the xml file. 到目前为止,我的代码仅适用于父节点的子节点,而我需要检查子节点的所有子节点,我完全不了解如何遍历xml文件的所有元素。

Modify your code to make use of recursion properly. 修改您的代码以正确使用递归。 You need to ALWAYS recurse, not only if a tag has the name you are looking for, because the children still might have the name you are looking for. 您需要始终递归,不仅仅是标签具有您要查找的名称,因为孩子们仍然可能拥有您正在寻找的名称。 Also, you need to add the result of the recursive call to the sum. 此外,您需要将递归调用的结果添加到总和中。 Something like this: 像这样的东西:

private static int tagCount(XMLTree xml, String tag) {
    assert xml != null : "Violation of: xml is not null";
    assert tag != null : "Violation of: tag is not null";

    int count = 0;

    if (xml.isTag()) {
        for (int i = 0; i < xml.numberOfChildren(); i++) {
            if (xml.child(i).label().equals(tag)) {
                count++;
            }
            count = count + tagCount(xml.child(i), tag);
        }
    }
    return count;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM