Starfire Starfire - 5 months ago 24
Java Question

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. 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.

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++;
tagCount(xml.child(i), tag);
}
}
}
return count;

}

Answer

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;
}
Comments