简体   繁体   中英

XML Child Node count - Java

I need to get the count of the number of child nodes underneath a parent tag <test> in the below example.

So count of <username> , <password> and <result> = 3.

<TestData>
    <test>
        <username>test1234</username>
        <password>fake</password>
        <result>Incorrect Login or Password</result>
    </test>
    <test>
        <username>abc</username>
        <password>1234</password>
        <result/>
    </test>
</TestData>

I have managed to get the count of <test> as follows;

NodeList nList = doc.getElementsByTagName("test");
TEST_CASE_COUNT = nList.getLength();

Now I need the count of the child nodes within <test>

To get the number of child elements within a particular element, you need to take account of the fact that not all nodes are elements. For example, you could use:

static int getChildElementCount(Element element) {
    int count = 0;
    NodeList childNodes = element.getChildNodes();
    for (int i = 0; i < childNodes.getLength(); i++) {
        if (childNodes.item(i).getNodeType() == Node.ELEMENT_TYPE) {
            count++;
        }
    }
    return count;
}

There may be a simpler way using XPath to select just elements, too. (I rarely find XPath a simpler solution, but YMMV.)

I think what you're looking for is Node.getChildNodes() . You would have to loop through your list of <test> and then count the children for each one, adding them as you go.

NodeList nList = doc.getElementsByTagName("test"); 
int TEST_CASE_COUNT = nList.getLength();
int nodeCount = 0;
for (int i = 0; i < nList.getLength(); i++) {
    Node test = nList.item(i);
    nodeCount += test.getChildNodes().getLength();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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