[英]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.