Andrius
Andrius

Reputation: 21188

Java - NodeList can't get Childnode

I don't understand how to get child node parsing xml file with java. 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. 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?

You can find xml file using this link:

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

Upvotes: 0

Views: 3659

Answers (2)

A4L
A4L

Reputation: 17595

You need to check the node type of the actual node.

#text is also a node! but you are probably looking for the type Element

Get the node list from your document using Document#getElementsByTagName and iterate over it. Check the type of each node to identify the ones you are interested in.

Upvotes: 0

pasha701
pasha701

Reputation: 7207

Element "stock" contains text, which is returned as first child. 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());
        }

Upvotes: 3

Related Questions