简体   繁体   English

无法从Java xml解析器中的当前节点获取NodeList

[英]Can't get NodeList from current node in java xml parser

So, I have this xml file: 所以,我有这个xml文件:

<Network id="TestSet01" description="Simple test set to begin development">
  <node_list>
    <node id="n0"/>
    <node id="n1"/>
    <node id="n2"/>
  </node_list>
</Network>

And i have this code: 我有这段代码:

try {
        File inputFile = new File("TestSet01_Network.xml");
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(inputFile);
        doc.getDocumentElement().normalize();

        NodeList rList = doc.getElementsByTagName("Network");

        for (int h = 0; h < rList.getLength(); h++) {
            Node rNode = rList.item(h);

            String name = ((Element) rNode).getAttribute("id");

            String description = ((Element) rNode).getAttribute("description");                               

            NodeList nList = ((Element) rNode).getElementsByTagName("node_list"); //Doesn't work properly here
            for (int i = 0; i < nList.getLength(); i++) {
                //code
            }
    } catch (ParserConfigurationException | SAXException | IOException e) {
    }

The problem I'm having is that I can't seem to get the NodeList containing the child nodes of the "node_list" node so I can iterate them individually in the "for" loop after. 我遇到的问题是,我似乎无法获得包含“ node_list”节点的子节点的NodeList,因此之后可以在“ for”循环中分别对其进行迭代。 The code seems to be correct but the list isn't right. 该代码似乎是正确的,但列表不正确。 I marked the line where I'm having this problem. 我在出现此问题的地方标记了一行。

 NodeList rList = doc.getElementsByTagName("Network");

will return you the List containing 1 child : ... 将返回包含1个孩子的列表:...

and nodes are actually it's children So you just need to go 1 level deeper before starting a loop 和节点实际上是孩子,所以您只需要在开始循环之前再深入1级

Element root = doc.getDocumentElement(); //Network
            for (int i = 0; i < root.getChildNodes().getLength(); i++) {
                Node n = root.getChildNodes().item(i);
                if (n instanceof Element) {
                    NodeList nodes = n.getChildNodes();
                    for (int j = 0; j < nodes.getLength(); j++) {
                        Node theNode = nodes.item(j);
                        if (theNode instanceof Element) {
                            System.out.println(((Element) theNode).getAttribute("id"));
                        }
                    }
                }
            }

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

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