Null Pointer Exception in XMl Parsing

前端 未结 4 702
礼貌的吻别
礼貌的吻别 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:43

    Just check that the object is not null:

    private static String getTagValue(String tag, Element eElement) {
        NodeList nlList = eElement.getElementsByTagName(tag).item(0).getChildNodes();
        Node nValue = (Node) nlList.item(0);
        if(nValue == null) 
            return null;
        return nValue.getNodeValue();
    }
    
    String salary = getTagValue("Department", eElement);
    if(salary != null) {
        System.out.println("Salary : " + getTagValue("Department", eElement));
    }
    

提交回复
热议问题