【问题标题】:XML Parsing - Null Object Reference - AndroidXML 解析 - 空对象参考 - Android
【发布时间】:2018-07-13 10:48:36
【问题描述】:

我正在解析 XML 数据,但是当在 XML 中是没有文本的标记时(仅 <item/> )它会写入错误:

java.lang.NullPointerException:尝试调用接口方法 空对象上的“java.lang.String org.w3c.dom.Node.getNodeValue()” 参考

这是我得到错误的函数:

private static String getNode(String sTag, Element eElement) {
    NodeList nlList = eElement.getElementsByTagName(sTag).item(0)
            .getChildNodes();
    Node nValue = (Node) nlList.item(0);
    return nValue.getNodeValue(); //here I get error
}

有人可以帮我解决这个问题吗? 非常感谢。

【问题讨论】:

  • 检查null 是否为空return 值是否为null 返回其他值,例如空String
  • nlList.item(0) 存在,并不代表它不为空

标签: java android xml nullpointerexception


【解决方案1】:

出现此问题是因为 nValuenull。 您需要决定您的方法在这种情况下应该如何操作并使用此代码

if(nValue!=null)
{
    return nValue.getNodeValue();
}
else
{
    //the tag has no value
    //return other default value or maybe throw your own exception 
}

【讨论】:

  • 这是我的荣幸!
猜你喜欢
  • 2017-08-25
  • 2022-10-02
  • 1970-01-01
  • 1970-01-01
  • 2023-04-05
  • 1970-01-01
  • 2020-06-11
  • 1970-01-01
  • 2020-03-01
相关资源
最近更新 更多