Java 从 xml 递归读取节点仅返回 #text 节点

标签 java xml recursion

我使用此方法从 xml 文件读取所有节点。但看来我的递归不起作用,因为所有节点都是#text 节点。我怎样才能跳过它并让它返回我的实际节点?

private void iterateNodes(Node node) {

    System.out.println("Node: " + node.getNodeName());

    NodeList nodeList = node.getChildNodes();

    for (int i = 0; i < nodeList.getLength(); i++) {
        Node currentode = nodeList.item(0);

        System.out.println(currentode.getNodeName());

        if (currentode.getNodeType() == Node.ELEMENT_NODE) {

            Element element = (Element) currentode;
            iterateNodes(element);
        }
    }
}

public void run() throws ParserConfigurationException, SAXException, IOException {

    String path = "others.xml";

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    org.w3c.dom.Document document = builder.parse(path);

    document.getDocumentElement().normalize();

    iterateNodes(document.getDocumentElement());

}

最佳答案

您在Node currentode = nodeList.item(0) 中进行编码 <---- 使用迭代器变量 i 更改它。

private void iterateNodes(Node node) {

    System.out.println("Node: " + node.getNodeName());
    NodeList nodeList = node.getChildNodes();

    for (int i = 0; i < nodeList.getLength(); i++) {
        Node currentode = nodeList.item(i);

        System.out.println(currentode.getNodeName());

        if (currentode.getNodeType() == Node.ELEMENT_NODE) {
            Element element = (Element) currentode;
            iterateNodes(element);
        }
    }
}

关于Java 从 xml 递归读取节点仅返回 #text 节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35148704/

相关文章:

java - 查看Session、Application和Request Bean的内容

java - 如何: BitmapRegionDecoder using String pathName to the drawable directory

java - 如何使用 OkHttpClient MockWebSever 返回图像/字节[]?

java - 如何使用 Java 从属性 xml 中获取值?

xml - 如何返回 QDomDocument 中的根元素?

recursion - Lisp逆向 "all"函数

c - 使用递归创建哈希码函数

Java/Scala Kafka Producer 不向主题发送消息

java - Oracle xdb-xmlparser 源代码

java - Java 中的递归冒泡排序