Why am I getting extra text nodes as child nodes of root node?

前端 未结 1 1086
情书的邮戳
情书的邮戳 2020-12-29 05:10

I want to print the child elements of the root node. This is my XML file.




   

        
1条回答
  •  礼貌的吻别
    2020-12-29 05:24

    Why the three text nodes are coming over here ?

    They're the whitespace between the child elements. If you only want the child elements, you should just ignore nodes of other types:

    for (int i = 0;i < nList.getLength(); i++) {
        Node node = nList.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            System.out.println("node name: " + node.getNodeName());
        }
    }
    

    Or you could change your document to not have that whitespace.

    Or you could use a different XML API which allows you to easily ask for just elements. (The DOM API is a pain in various ways.)

    If you only want to ignore element content whitespace, you can use Text.isElementContentWhitespace.

    0 讨论(0)
提交回复
热议问题