在Java中读取XML时的空指针

时间:2013-04-09 16:16:12

标签: java xml xml-parsing w3c

我试图从jave中的xml文件中获取所有作者,这里是xml代码

<?xml version="1.0"?>
<map>
<authors>
    <author>testasdas</author>
    <author>Test</author>
</authors>
</map>

这是我在Java中使用的代码

public static List<String> getAuthors(Document doc) throws Exception {
    List<String> authors = new ArrayList<String>();
    Element ed = doc.getDocumentElement();
    if (notExists(ed, "authors")) throw new Exception("No authors found");
    Node coreNode = doc.getElementsByTagName("authors").item(0);
    if (coreNode.getNodeType() == Node.ELEMENT_NODE) {
        Element coreElement = (Element) coreNode;
        NodeList cores = coreElement.getChildNodes();
        for (int i = 0; i < cores.getLength(); i++) {
            Node node = cores.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                Element e = (Element) node;
                String author = e.getElementsByTagName("author").item(i).getTextContent();
                Bukkit.getServer().broadcastMessage("here");
                authors.add(author);
            }
        }
    }
    return authors;
}

我在尝试运行代码时收到java.lang.NullPointerException错误,但我不确定原因。

  

09.04 17:05:24 [服务器] SEVERE at com.dcsoft.arenagames.map.XMLHandler.getMapData(XMLHandler.java:42)
  09.04 17:05:24 [服务器] SEVERE at com.dcsoft.arenagames.map.XMLHandler.getAuthors(XMLHandler.java:73)
  09.04 17:05:24 [服务器] SEVERE java.lang.NullPointerException

2 个答案:

答案 0 :(得分:1)

问题是您的代码使用<author>i节点列表建立索引,<authors>计算<author>标记的所有子标记,其中一些不是item(i)元素。当null返回getTextContent()时,当您尝试拨打public static List<String> getAuthors(Document doc) throws Exception { List<String> authors = new ArrayList<String>(); NodeList authorNodes = doc.getElementsByTagName("author"); for (int i = 0; i < authorNodes.getLength(); i++) { String author = authorNodes.item(i).getTextContent(); Bukkit.getServer().broadcastMessage("here"); authors.add(author); } return authors; } 时会收到NPE。你也不需要做所有的导航(看起来有点可疑,而且肯定令人困惑)。试试这个:

{{1}}

答案 1 :(得分:1)

要查找java.lang.NullPointerException的原因,请在发生异常的行上设置断点,在这种情况下为73,并调查该行上的变量。

我的猜测是你的代码行:

String author = e.getElementsByTagName("author").item(i).getTextContent()

变量eauthor元素,因此e.getElementsByTagName("author")返回null的原因。