[英]Null pointer exception when reading xml file
I have a class named xmlReader
that have parse(String path)
and parseXml(Document doc)
methods. 我有一个名为
xmlReader
的类,该类具有parse(String path)
和parseXml(Document doc)
方法。 I define: 我定义:
xmlReader reader = new xmlReader();
Document doc = reader.parse(PATH);
reader.parseXml(doc);`
My parseXml
method: 我的
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());
}
}
The problem: line 3 of parseXml
method: 问题:
parseXml
方法的第3行:
When Node id = att.item(0)
the program get a null ref exception. 当
Node id = att.item(0)
,程序将获得null ref异常。 When debugging I see that the doc is defined null
. 调试时,我看到doc定义为
null
。 Why is that? 这是为什么? Its like its not reading the file correctly.
就像没有正确读取文件一样。
Thanks? 谢谢?
This is my parse(String path) method: 这是我的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;
}
Take a look at http://docs.oracle.com/javase/1.5.0/docs/api/org/w3c/dom/Node.html#getAttributes () 看看http://docs.oracle.com/javase/1.5.0/docs/api/org/w3c/dom/Node.html#getAttributes ()
Before you do this Node id = att.item(0);
在执行此操作之前,
Node id = att.item(0);
take a look at the object type of Node first
by doing System.out.println(first);
Node first
通过执行System.out.println(first);
来查看Node first
的对象类型System.out.println(first);
your probably going to see that this is a text element and not an element. 您可能会发现这是一个文本元素,而不是元素。
What you've done when you said Node first = doc.getFirstChild().getFirstChild();
当您说
Node first = doc.getFirstChild().getFirstChild();
时,您所做的事情 is "give me the first child of the first element, which is probably a text element. What you should be doing is checking for ELEMENT nodes like this, only Node.ELEMENT_NODE
will have non-null for getAttributes()
: 是“给我第一个元素的第一个孩子,它可能是一个文本元素。您应该做的是检查像这样的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.