简体   繁体   中英

XML Parser : How to avoid null pointer exception

when given key is not exist it throws NPE .

String nodeValue = eElement.getElementsByTagName(key).item(0).getTextContent();
    if (nodeValue == null || nodeValue.isEmpty())
        return null;
    return nodeValue;`
Try this

 String nodeValue=null;     
if(eElement!=null && eElement.getElementsByTagName(key)!=null     
 && eElement.getElementsByTagName(key).item(0)!=null ){
 nodeValue = eElement.getElementsByTagName(key).item(0).getTextContent();
}
return nodeValue;

Check if any of the element of your expression is null

String nodeValue = null;
if (eElement != null && eElement.getElementsByTagName(key) != null && eElement.getElementsByTagName(key).length > 0) {
    nodeValue = eElement.getElementsByTagName(key).item(0).getTextContent();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM