0

I'm just starting out with learning how to process/parse XML data in Java. I'm getting the error, "The method getNodeType() is undefined for the type NodeList" on the line, after my for-loop, that contains:

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

The type of error seems like I forgot to import something, but I believe I got everything. I am using an XML example from microsoft, in the following link:

http://msdn.microsoft.com/en-us/library/ms762271(v=vs.85).aspx

Thanks in advance.

import java.io.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Element;

public class Files {

    public static void main (String [] args) throws IOException, ParserConfigurationException{

    String address = "/home/leo/workspace/Test/Files/src/file.xml";

    File xmlFile = new File(address);

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = factory.newDocumentBuilder();
    Document doc = dBuilder.parse(xmlFile);

    doc.getDocumentElement().normalize();

    System.out.println(doc.getDocumentElement().getNodeName());

    NodeList n = doc.getElementsByTagName("book id");

    for (int temp = 0; temp < n.getLength(); temp++){
        System.out.println(n.item(temp));

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

        Element e = (Element) n;

        System.out.println("author : " + e.getAttribute("author"));
        System.out.println("title : " + e.getAttribute("title") );
        System.out.println("genre : " + e.getAttribute("genre"));
        System.out.println("price : " + e.getAttribute("price"));
        System.out.println("publish_date : " + e.getAttribute("publish_date"));
        System.out.println("description : " + e.getAttribute("description"));

             }
        }

    }   

}

1 Answer 1

1

You are calling getNodeType() on a NodeList object (n).

You need to call this function on a Node object. Example :

n.item(temp).getNodeType();
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, that fixed the error. As I said before, I'm new to XML parsing in Java, and am just following online code/tutorials. I am currently only printing out "catalog." If you, or someone else could point me in the right direction, it would be appreciated.
@user2411290 You should post another question about this problem since this one was about the getNodeType() function. Also, please consider accepting this solution if it worked for you. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.