I get an error when i run the beginning of my XML reader:
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 is giving me the following output:
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)
Could someone开发者_如何学编程 help me figure this one out?
You're not checking if there IS an element 0. Essentially, .item() will return null if the index isn't valid, as such there may not be an item with index 0 which returns null and then you try to call getChildNodes() on the null pointer. Hence your NPE.
You should be iterating over the elements in the node list.
change
Element nameElement = (Element)nameList.item(0);
to
for(int x = 0; x < nameList.getLength(); x++) {
nameElement = nameList.item(x);
NodeList nameOutput = nameElement.getChildNodes();
System.out.println("name: "+nameElement);
}
精彩评论