java XML 解析中的空指针异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11828560/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 06:32:17  来源:igfitidea点击:

Null Pointer Exception in XMl Parsing

javaxmlxml-parsing

提问by Jean Logeart

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:

我需要解析一个 Xml 文档并将值存储在文本文件中,当我解析普通数据时(如果所有标签都有数据)那么它工作正常,但是如果任何标签没有数据那么它会抛出我需要的“空指针异常”要做,为了避免空指针异常,请建议我使用示例代码示例 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();
  }

}

回答by Jean Logeart

Just check that the object is not null:

只需检查对象不是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));
}

回答by JB Nizet

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

上面的行从空节点列表中获取第一个元素。由于列表为空,0 是无效索引,根据文档,返回 null

return nValue.getNodeValue();

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

因此,上面的行调用了一个空变量上的方法,这会导致 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();

回答by Massimiliano Giunchi

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

回答by Sungray

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.

其他标签也一样。