当我运行XML阅读器的开头时出现错误:
public static void main(String[] args)
{
System.out.println("XML Reader");
try
{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse("database.xml");
//normalize text
doc.getDocumentElement().normalize();
System.out.println("The root of this doc is "+doc.getDocumentElement().getNodeName());
NodeList listOfAddresses = doc.getElementsByTagName("address");
int totalAddresses = listOfAddresses.getLength();
System.out.println(totalAddresses+" addresses in "+ doc.getDocumentElement().getNodeName());
//main loop
for(int i = 0; i<listOfAddresses.getLength(); i++)
{
Node items = listOfAddresses.item(i);
if(items.getNodeType() == Node.ELEMENT_NODE)
{
System.out.println("Address #"+i);
Element element = (Element)items;
NodeList nameList = element.getElementsByTagName("name");
Element nameElement = (Element)nameList.item(0);
NodeList nameOutput = nameElement.getChildNodes();
System.out.println("name: "+nameElement);
}
}
}
catch(SAXParseException err)
{
System.out.println("Sax Parse Exception error on line "+err.getLineNumber());
}
catch(SAXException e)
{
System.out.println("SAX Exception error");
Exception x = e.getException();
((x == null) ? e : x).printStackTrace();
}
catch(Throwable t)
{
System.out.println("Trowable error");
t.printStackTrace();
}
}
netbeans给了我以下输出:
run: XML Reader The root of this doc is database 2 addresses in database java.lang.NullPointerException Address #0 Trowable error at xmlreader.XMLreader.main(XMLreader.java:42)
有人可以帮我解决这个问题吗?
答案 0 :(得分:2)
你没有检查是否有一个元素0.本质上,如果索引无效,.item()将返回null,因此可能没有索引0的项返回null然后你尝试在空指针上调用getChildNodes()。因此你的NPE。
您应该迭代节点列表中的元素。
变化
Element nameElement = (Element)nameList.item(0);
到
for(int x = 0; x < nameList.getLength(); x++) {
nameElement = nameList.item(x);
NodeList nameOutput = nameElement.getChildNodes();
System.out.println("name: "+nameElement);
}