如何为节点列表获取Java中重复元素的子节点 [英] How to fetch the child nodes of repeated elements in java for nodelist

查看:95
本文介绍了如何为节点列表获取Java中重复元素的子节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要获取 name 元素的值,该元素是 e 元素的子元素:

I need to fetch the value of the name element which is a child of an e element:

<a>
    <b>
        <c>
            <d>
                <e><name>123</name></e>
                <e><name>456</name></e>
                <e><name>456</name></e>
            </d>
        </c>
    </b>
</a>

这是我的代码:

NodeList lineItemAttributeChildrenList =
    doc.getElementsByTagName("e").item(0).getChildNodes();

if(lineItemAttributeChildrenList != null &&
   lineItemAttributeChildrenList.getLength() > 0) {
    System.out.println("Inside if and checking length" +
                       lineItemAttributeChildrenList.getLength());

    for (int i = 0; i < lineItemAttributeChildrenList.getLength(); i++) {
        System.out.println("i " + i);
        System.out.println("inside for");
        System.out.println("name==============" +
                           lineItemAttributeChildrenList.item(i).getNodeName());
        System.out.println("value==============" +
                           lineItemAttributeChildrenList.item(i).getTextContent());
    }
}

从上面的代码中,我仅获得第一个内部元素 e 元素的名称值,但对于其余2个,我无法获取这些值。它不会转到for循环中的第二个 e 元素。

From the above code I just get the first inner element name value for the e element, but for the remaining 2 I am not able to get those values. It is not going to the second e element in the for loop.

推荐答案

您正在获得 e个元素的NodeList的第0个元素。

You are getting 0th element of the NodeList of "e" elements.

    NodeList LineItemAttributeChildrenList = doc.getElementsByTagName("e").item(0).getChildNodes();
...
 for (int i = 0; i < LineItemAttributeChildrenList.getLength(); i++) {

您应该遍历NodeList本身,而不要遍历第一个元素的孩子。以下是新代码的外观:

You should iterate through the NodeList itself instead of the children of the first element. Here is how your new code would look:

    NodeList LineItemAttributeChildrenList = doc.getElementsByTagName("e");
    if (LineItemAttributeChildrenList != null && LineItemAttributeChildrenList.getLength() > 0) 
    {
        System.out.println("Inside if and checking length"+LineItemAttributeChildrenList.getLength());
        for (int i = 0; i < LineItemAttributeChildrenList.getLength(); i++) {
            System.out.println("i "+i);
            System.out.println("inside for");
            System.out.println("name=============="+LineItemAttributeChildrenList.item(i).getNodeName());
            System.out.println("value=============="+LineItemAttributeChildrenList.item(i).getTextContent());
        }
     }

这篇关于如何为节点列表获取Java中重复元素的子节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆