Trying to parse XML data with Java - Getting error: "The method getNodeType() is undefined for the type NodeList"



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://ift.tt/1jtIGN3


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"));

}
}

}

}

No comments:

Post a Comment