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>

Jon Skeet
people
quotationmark

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

people

See more on this question at Stackoverflow