出现的问题是:
编译通过,运行出错,报出的错误是:
Exception in thread "main" java.lang.NullPointerException
以下是java代码,
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
public class DOMStudentinfo
{
public static void main(String [] args)
{
//得到DOM解析器工厂类的实例
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
try
{
//得到具体厂商的DOM解析器实例
DocumentBuilder db=dbf.newDocumentBuilder();
File file=new File("students.xml");
//得到整个XML文档的文档对象
Document doc=db.parse(file);
//得到文档中所有的student元素
NodeList nl=doc.getElementsByTagName("student");
//得到student元素的个数
int len=nl.getLength();
System.out.println(len);
for(int i=0;i<len;i++)
{
//第一轮循环,得到第一个student元素
//item方法返回的是Node对象,需要向下转型为Element
Element eltStu=(Element)nl.item(i);
//得到name子元素和age子元素
Node eltName=eltStu.getElementsByTagName("name").item(i);
Node eltAge=eltStu.getElementsByTagName("age").item(i);
//得到文本节点的内容
String name=eltName.getFirstChild().getNodeValue();
String age=eltAge.getFirstChild().getNodeValue();
System.out.print("姓名: ");
System.out.println(name);
System.out.print("年龄: ");
System.out.println(age);
System.out.println("=========================");
}
}
catch(ParserConfigurationException e)
{
e.printStackTrace();
}
catch(SAXException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
我怎么找也找不到原因,有哪位好心人帮忙吗?