这是我要解析的 xml
<metadata>
<groupId>org.chromium</groupId>
<artifactId>chromedriver-win32</artifactId>
<versioning>
<release>2.14</release>
<versions>
<version>2.14</version>
</versions>
<lastUpdated>20150610112540</lastUpdated>
</versioning>
</metadata>
当我尝试解析上述 XML 时,即使我已经处理了 null 检查,我仍然收到 NullPointerException
。下面是代码
private String getVersionFromNode(Element eElement) {
String version = null;
// Get the latest version
String tagName = "latest";
try {
version = eElement.getElementsByTagName(tagName).item(0).getTextContent();
// If latest version is not available take the release
// version
if ( version.isEmpty() || null == version || "null" == version) {
tagName = "release";
version = eElement.getElementsByTagName(tagName).item(0).getTextContent();
}
}
catch (NullPointerException e) {
System.out.println("not able to parse " + tagName + " tag " + e.getMessage());
}
return version;
}
当版本为空时,应该进入下面的 block 。
if ( version.isEmpty() || null == version || "null" == version) {
tagName = "release";
version = eElement.getElementsByTagName(tagName).item(0).getTextContent();
}
这个问题应该怎样解决?
最佳答案
您的String tagName
是“latest”
,并且在您的xml文件中,没有名为latest
的元素,因此您的版本
仍然是 null
,因此当以下代码时会生成 NullPointerException
:
version.isEmpty()
在您的if
语句中执行。因为version
是null
。并且您的代码尝试检查 null
是否为空。但它不能。因此,这里生成了一个 NullPointerException 异常。
要处理这种情况,首先检查version
是否为null
。其次检查字符串 version
是否等于字符串 "null"
。第三,检查是否为空。因此,将 if
语句中的条件顺序更改为:
if ( version.isEmpty() || null == version || "null" == version)
到
if (null == version || "null" == version || version.isEmpty())
顺便说一句,作为附带提示,请使用:
"null".equals(version)
而不是
"null" == version
关于java - 解析 xml 时避免空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30932886/