尝试使用Java解析XML数据 - 获取错误:"方法getNodeType()未定义类型NodeList"

时间:2014-07-28 15:53:11

标签: java xml

我刚开始学习如何使用Java处理/解析XML数据。我收到错误,“方法getNodeType()未定义类型NodeList ”,在我的for循环之后,包含:

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

错误的类型似乎我忘了导入一些东西,但我相信我得到了一切。我正在使用microsoft的XML示例,在以下链接中:

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

提前致谢。

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 个答案:

答案 0 :(得分:1)

您正在getNodeType()对象(n)上调用NodeList

您需要在Node对象上调用此函数。示例:

n.item(temp).getNodeType();