有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

无法从java xml解析器中的当前节点获取节点列表

我有一个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>

我有这个密码:

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) {
    }

我遇到的问题是,我似乎无法获取包含“node_list”节点的子节点的NodeList,以便在之后的“for”循环中逐个迭代它们。代码似乎正确,但列表不正确。我标出了我遇到这个问题的地方


共 (1) 个答案

  1. # 1 楼答案

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

    将返回包含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"));
                            }
                        }
                    }
                }