[英]Null pointer exception when reading xml file
我有一個名為xmlReader
的類,該類具有parse(String path)
和parseXml(Document doc)
方法。 我定義:
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());
}
}
問題: parseXml
方法的第3行:
當Node id = att.item(0)
,程序將獲得null ref異常。 調試時,我看到doc定義為null
。 這是為什么? 就像沒有正確讀取文件一樣。
謝謝?
這是我的parse(String path)方法:
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;
}
看看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
的對象類型System.out.println(first);
您可能會發現這是一個文本元素,而不是元素。
當您說Node first = doc.getFirstChild().getFirstChild();
時,您所做的事情 是“給我第一個元素的第一個孩子,它可能是一個文本元素。您應該做的是檢查像這樣的ELEMENT節點,只有Node.ELEMENT_NODE
的getAttributes()
會為非null:
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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.