Null Pointer Exception in XMl Parsing

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

    Replace

    System.out.println("First Name : " + getTagValue("firstname", eElement));
    

    by

    System.out.println("First Name : " + getTagValue("firstname", eElement) == null?"":getTagValue("firstname", eElement));
    

    same thing for the other tags.

    0 讨论(0)
  • 2021-01-13 23:29

    This code should work:

    // getNode function
    private static String getNode(String sTag, Element eElement) {
        //if sTag exists(not null) I get childNodes->nlList
        if (eElement.getElementsByTagName(sTag).item(0)!=null){
            NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
            //check if child (nlList) contain something
            if ((nlList.getLength() == 0))//if the content is null
                return "";
            //if child contains something extract the value of the first element
            Node nValue = (Node) nlList.item(0);
                return nValue.getNodeValue();
        }
        return "";
    }
    
    0 讨论(0)
  • 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();
    
    0 讨论(0)
  • 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));
    }
    
    0 讨论(0)
提交回复
热议问题