Null Pointer Exception in XMl Parsing

2019-02-18 16:54发布

问题:

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 data then it throwing "Null pointerException" what i need to do, to avoid null pointer exception, please suggest me with sample codes Sample xml:

<company>
    <staff>
        <firstname>John</firstname>
        <lastname>Kaith</lastname>
        <nickname>Jho</nickname>
        <Department>Sales Manager</Department>
    </staff>
    <staff>
        <firstname>Sharon</firstname>
        <lastname>Eunis</lastname>
        <nickname></nickname>
        <Department></Department>
    </staff>
    <staff>
        <firstname>Shiny</firstname>
        <lastname>mack</lastname>
        <nickname></nickname>
        <Department>SAP Consulting</Department>
    </staff>
</company>

code:

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;

public class ReadXMLFile {

    public static void main(String argv[]) {

      try {

        File fXmlFile = new File("c:\\file.xml");
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(fXmlFile);
        doc.getDocumentElement().normalize();

        System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
        NodeList nList = doc.getElementsByTagName("staff");
        System.out.println("-----------------------");

        for (int temp = 0; temp < nList.getLength(); temp++) {

           Node nNode = nList.item(temp);
           if (nNode.getNodeType() == Node.ELEMENT_NODE) {

              Element eElement = (Element) nNode;

              System.out.println("First Name : " + getTagValue("firstname", eElement));
              System.out.println("Last Name : " + getTagValue("lastname", eElement));
                  System.out.println("Nick Name : " + getTagValue("nickname", eElement));
              System.out.println("Salary : " + getTagValue("Department", eElement));

           }
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
  }

  private static String getTagValue(String sTag, Element eElement) {
    NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();

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

    return nValue.getNodeValue();
  }

}

回答1:

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));
}


回答2:

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();


回答3:

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.



回答4:

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 "";
}