Java文件uri与xml文件空指针异常
我使用的是Windows操作系统, 并想要解析 xml 文件,但出现空指针错误...
public void print( )
throws SAXException, IOException {
DocumentBuilder builder;
Document document = builder.parse( "D:\\my\\xml.xml");//null pointer exception
}
这是解决方案:
public class DOMPrinter {
private DocumentBuilder builder;
public void print(String fileName )//, PrintStream out)
throws SAXException, IOException {
try
{
DocumentBuilderFactory fact= DocumentBuilderFactory.newInstance();
builder= fact.newDocumentBuilder();
Document document = builder.parse( fileName);
Node node = document.getDocumentElement();
String root = node.getNodeName();
System.out.println("Root Node: " + root);
}
catch (Exception e) {
// TODO: handle exception
}
}
我没有使用 DocumentBuilderFactory 来创建 DocumentBuilder ,所以这是一个错误。
I am using windows OS,
and want to parse xml file, but get null pointer error....
public void print( )
throws SAXException, IOException {
DocumentBuilder builder;
Document document = builder.parse( "D:\\my\\xml.xml");//null pointer exception
}
here is the solution:
public class DOMPrinter {
private DocumentBuilder builder;
public void print(String fileName )//, PrintStream out)
throws SAXException, IOException {
try
{
DocumentBuilderFactory fact= DocumentBuilderFactory.newInstance();
builder= fact.newDocumentBuilder();
Document document = builder.parse( fileName);
Node node = document.getDocumentElement();
String root = node.getNodeName();
System.out.println("Root Node: " + root);
}
catch (Exception e) {
// TODO: handle exception
}
}
I didn't use DocumentBuilderFactory to create DocumentBuilder , so that was a error.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您从未实例化
builder
。你需要说builder = ...
;另外,方法内不能有私有字段。删除 private 关键字。
You never instantiated
builder
. You need to saybuilder = ...
;Also, you can't have private fields inside a method. Delete the private keyword.