首页 > 解决方案 > 使用 xml 解析时显示 null 的文档

问题描述

解析文档时出现错误。它显示一个空文档

错误:[请求处理失败;嵌套异常 java.lang.NullPointerException] 与根本原因 java.lang.NullPointerException

String subBuildFile = "E:\Data Sync 4.4\WEB-INF\Temp_Project\Project_3";
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); 
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new InputSource(subBuildFile));
Node s = doc.getElementsByTagName("userList").item(1);
for(int i =2; i < doc.getElementsByTagName("user").getLength(); i++) {
    doc.getElementsByTagName("userList").item(i)
        .removeChild(doc.getElementsByTagName("userList").item(i));
}

标签: javaxmldomnullpointerexceptiondocument

解决方案


你的问题是你使用InputSource不正确。

您正在调用new InputSource(String)并且该构造函数是这样说的:

/**
 * Create a new input source with a system identifier.
 * ...
 * If the system identifier is a URL, it must be fully
 * resolved (it may not be a relative URL).
 *
 * @param systemId The system identifier (URI).
 */
 public InputSource (String systemId){...}

而是使用此构造函数:

/** Create a new input source with a character stream. */
public InputSource (Reader characterStream) { ... }

并像这样使用它:

Document doc = dBuilder.parse(new InputSource(new StringReader(subBuildFile)));

推荐阅读