2012-01-09 113 views
0

我有一个名为xmlReader的类,它有parse(String path)parseXml(Document doc)方法。 我定义:读取xml文件时空指针异常

xmlReader reader = new xmlReader(); 
    Document doc = reader.parse(PATH); 
    reader.parseXml(doc);` 

parseXml方法:

public void parseXml(Document doc) 
{ 
    Node first = doc.getFirstChild().getFirstChild(); 
    NamedNodeMap att = first.getAttributes(); 
    Node id = att.item(0); 
    NodeList l = first.getChildNodes(); 
    System.out.println("id:" + id.getNodeValue()); 
    for(int i = 0; i < l.getLength(); i++) 
    { 
     Node temp = l.item(i); 
     System.out.println(temp.getNodeName() + ": " + 
       temp.getNodeValue()); 
    } 

} 

问题:3号线parseXml的方法:

Node id = att.item(0)程序得到一个空REF例外。在调试时,我发现文档被定义为null。这是为什么? 它就像它没有正确读取文件。

谢谢?

这是我的解析(字符串路径)方法:

public Document parse(String path) 
{ 
DocumentBuilderFactory dbf = 
DocumentBuilderFactory.newInstance(); 
DocumentBuilder db = null; 

try 
{ 
    db = dbf.newDocumentBuilder(); 
} catch (ParserConfigurationException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 
Document doc = null; 
try 
{ 
    doc = db.parse(path); 
} catch (SAXException e) { 

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

    e.printStackTrace(); 
} 
return doc; 
} 
+3

“这就像它无法正确读取该文件。”嗯,也许它不能正确读取该文件你怎么知道这不是问题 – Paul 2012-01-09 22:08:53

+3

你确定路径是正确的 – kosa 2012-01-09 22:09:31

+0

。?如果'doc'为'null',那么确实问题出在'doc = reader.parse(PATH);'不适用于你的方法。 – 2012-01-09 22:15:52

回答

3

看看http://docs.oracle.com/javase/1.5.0/docs/api/org/w3c/dom/Node.html#getAttributes()

在你做这个Node id = att.item(0);看一看的Node first对象类型做System.out.println(first);您可能会看到这是一个文本元素而不是元素。

当你说Node first = doc.getFirstChild().getFirstChild();时你所做的是“给我第一个元素的第一个孩子,它可能是一个文本元素。你应该做的是检查这样的ELEMENT节点,只有Node.ELEMENT_NODE将不具有非-null为getAttributes()

 NodeList nl = doc.getFirstChild().getChildNodes(); 
     for (int i = 0; i < nl.getLength(); i++){ 
      Node first = nl.item(i); 
      if (first.getNodeType() == Node.ELEMENT_NODE){ 
       System.out.println("first:" + first); 
       NamedNodeMap att = first.getAttributes(); 
       System.out.println("att:" + att); 
      } 

     }