You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用org.w3c.dom.Document.getDocumentElement()返回null引发空指针异常求助

问题分析与解决:创建XML时的NullPointerException

问题原因

通过dom.newDocument()创建的空Document对象没有根元素,getDocumentElement()方法用于返回文档的根元素,此时无元素可返回,所以返回null。调用null对象的appendChild()方法,必然触发空指针异常。

解决方法

直接使用Document对象的appendChild()方法,将你创建的根元素添加到文档中,无需先调用getDocumentElement()。

修改后的完整代码:

DocumentBuilderFactory docb = DocumentBuilderFactory.newInstance();
DocumentBuilder dom = docb.newDocumentBuilder();
Document doc = dom.newDocument();
Element raiz = doc.createElement("Alumnos");
// 直接将根元素添加至文档
doc.appendChild(raiz);

额外说明

  • getDocumentElement()仅在文档已有根元素时,才会返回有效的Element实例;
  • XML规范要求文档只能有一个根元素,后续的子节点都应该添加到这个根元素raiz上,而非直接添加到Document对象。

内容的提问来源于stack exchange,提问作者Mrex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 18:20:29