简体   繁体   English

XML子节点计数-Java

[英]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. 在下面的示例中,我需要获取父标记<test>下的子节点数。

So count of <username> , <password> and <result> = 3. 因此<username><password><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; 我设法获得了<test>的计数,如下所示;

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

Now I need the count of the child nodes within <test> 现在我需要<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. 使用XPath选择元素也可能有更简单的方法。 (I rarely find XPath a simpler solution, but YMMV.) (我很少发现XPath是更简单的解决方案,而是YMMV。)

I think what you're looking for is Node.getChildNodes() . 我认为您正在寻找的是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. 您将必须遍历<test>列表,然后对每个子项进行计数,并在添加时添加它们。

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();
}

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

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