Count repetitions of TAG in XML file

Asked

Viewed 217 times

1

Example of XML file:

<rec>
<v001>001</v001> 
<v002>2012609272311</v002>
<v003>616.890231</v003>
<v005>7</v005>
<v006>m</v006>
<v007>^a115001^b1^c1^d20100000^e2^fOvernight^m1</v007>
<v007>^a115002^b2^c1^d20100000^e1^m2</v007>
<v007>^a115003^b3^c1^d20100000^e1^m3</v007>
<v007>^a115004^b4^c1^d20100000^e1^m4</v007>
<v007>^a115005^b5^c1^d20100000^e1^m5</v007>
<v007>^a115006^b6^c1^d20100000^e1^m6</v007>
<v016>ROCHA, Ruth Mylius</v016>
<v018>Enfermagem em Saúde Mental</v018>
</rec>

The "rec" tags match there is a new record and I need to count how many times the v007 tag repeats within each rec. I’m using the following function:

static private int getCount(Node parentNode, String childName) {
    int qtdEx = 0;
    NodeList nList = parentNode.getChildNodes();
    for (int i = 0; i < nList.getLength(); i++) {
        Node n = nList.item(i);
        String name = n.getNodeName();
        if (name != null && name.equals(childName)) {
            return qtdEx++;
        }
    }
    return 0;

}

This function only returns me 0, I test as follows:

 NodeList nList = doc.getElementsByTagName("rec");

 for (int i = 0; i < nList.getLength(); i++) {
            Node node = nList.item(i);
            List<Object> columns = null;                                              
            columns = Arrays.asList(getCount(node, "v007"));
            }

If anyone can help, I’d appreciate it.

1 answer

1


I found the solution using the following function:

private static int getCount(Node parentNode) {
    int qtdEx = 0;
    NodeList nList = parentNode.getChildNodes();
    for (int i = 0; i < nList.getLength(); i++) {
        Node n = nList.item(i);
        String name = n.getNodeName();
        if ("v007".equals(name)) {
            qtdEx++;
        }
    }
    return qtdEx++;

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.