简体   繁体   English

Java-NodeList无法获取Childnode

[英]Java - NodeList can't get Childnode

I don't understand how to get child node parsing xml file with java. 我不明白如何使用Java获取子节点解析xml文件。 For example I have this code: 例如,我有以下代码:

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Parser {

    public static void main(String args[]) {

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



            NodeList nodes = doc.getElementsByTagName("stock");
            Node nodez = nodes.item(1);
            String s = nodez.getFirstChild().getNodeName(); //outputs #text?
                        System.out.println(s);
                        //If I try this
                        String s = nodez.getNodeName(); //outputs 'stock'


        } catch (Exception e) {
            e.printStackTrace();
        }
    }



}

So if I try to output current node name, it outputs properly, but if I try to output next child node name, it just outputs #text. 因此,如果我尝试输出当前节点名称,则会正确输出,但是如果我尝试输出下一个子节点名称,则只会输出#text。 How can I properly output any node I want? 如何正确输出所需的任何节点? I thought I could just use method as getFirstChild or getNextSibling , but it seems I'm doing something wrong? 我以为可以将方法用作getFirstChildgetNextSibling ,但是似乎我做错了什么?

You can find xml file using this link: 您可以使用以下链接找到xml文件:

http://javarevisited.blogspot.com/2011/12/parse-xml-file-in-java-example-tutorial.html http://javarevisited.blogspot.com/2011/12/parse-xml-file-in-java-example-tutorial.html

Element "stock" contains text, which is returned as first child. 元素“ stock”包含文本,该文本作为第一个子元素返回。 You can use folloving: 您可以使用以下方式:

        System.out.println(((Element) nodez).getElementsByTagName("symbol").item(0).getNodeName());
        // get all nodes
        NodeList nl=((Element) nodez).getElementsByTagName("*");
        for (int i = 0; i < nl.getLength(); i++) {
            System.out.println(nl.item(i).getNodeName());
        }

You need to check the node type of the actual node. 您需要检查实际节点的节点类型

#text is also a node! #text也是一个节点! but you are probably looking for the type Element 但您可能正在寻找Element类型

Get the node list from your document using Document#getElementsByTagName and iterate over it. 使用Document#getElementsByTagName从文档中获取节点列表并对其进行迭代。 Check the type of each node to identify the ones you are interested in. 检查每个节点的类型以标识您感兴趣的节点。

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

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