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

标签 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”循环中单独迭代它们。代码似乎是正确的,但列表不正确。我标记了遇到此问题的行。

最佳答案

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

关于java - 无法从 java xml 解析器中的当前节点获取 NodeList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34275640/

相关文章:

android - 未能找到内容提供商信息

android - 如何使用等同于特定 dp 的 rQuadTo 创建圆角路径?

c++ - 我该如何制作这个有效的 xml?

java - ANTLR(或替代): decoupling parsing from evaluation

java - 错误 :Execution failed for task ':app:transformClassesAndResourcesWithProguardForDebug'

java - 需要有关基本 Java 程序编译错误的帮助

php - 我在使用 simplexml 解析 facebook 提要时遇到问题

xml - 使用 XSLT 创建 SVG

java - 如何使JVM启动更快? [复制]

java - 使用 Spring 注释将值注入(inject) map