Null Pointer Exception in XMl Parsing

前端 未结 4 650
礼貌的吻别
礼貌的吻别 2021-01-13 23:00

I need to parser an Xml Document and store the values in Text File, when i am parsing normal data (If all tags have data) then its working fine, but if any tag doesnt have d

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-13 23:33

    NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
    

    The above line gets the child nodes of the element with the given tag name. If this element doesn't have data, the returned node list is empty.

    Node nValue = (Node) nlList.item(0);
    

    The above line gets the first element from the empty node list. Since the list is empty, 0 is an invalid index, and as per the documentation, null is returned

    return nValue.getNodeValue();
    

    The above line thus calls a method on a null variable, which causes the NPE.

    You should test if the list is empty, and return what you want (an empty string, for example), if it's the case:

    if (nList.getLength() == 0) {
        return "";
    }
    Node nValue = (Node) nlList.item(0);
    return nValue.getNodeValue();
    

提交回复
热议问题