【问题标题】:Null pointer when reading XML in Java在 Java 中读取 XML 时的空指针
【发布时间】:2013-04-01 04:37:26
【问题描述】:

我正在尝试从我的 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 [服务器] com.dcsoft.arenagames.map.XMLHandler.getMapData(XMLHandler.java:42) 严重 09.04 17:05:24 [服务器] com.dcsoft.arenagames.map.XMLHandler.getAuthors(XMLHandler.java:73)
09.04 17:05:24 [服务器] 严重的 java.lang.NullPointerException

【问题讨论】:

  • 完整的堆栈跟踪在哪里?
  • Try.. catch -> 堆栈跟踪?
  • XMLHandler.java 的第 73 行是哪一行?
  • 您应该在最初的问题中添加缺失的信息,而不是在 cmets 中;)

标签: java xml xml-parsing w3c


【解决方案1】:

要查找 java.lang.NullPointerException 的原因,请在发生异常的行(在本例中为 73)上设置断点并调查该行上的变量。

我的猜测是在你的代码行中:

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

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

【讨论】:

  • 如果e下没有&lt;author&gt;节点,getElementsByTagName不会返回null;它将返回一个空的NodeList。问题是如果i 超出范围,item(i) 会返回null
  • 当然,我认为结果是,原始代码一团糟,而您清理的版本正是我们所需要的。
【解决方案2】:

问题是您的代码使用i 索引&lt;author&gt; 节点列表,它计算&lt;authors&gt; 标记的所有子节点,其中一些不是&lt;author&gt; 元素。当item(i) 返回null 时,当您尝试调用getTextContent() 时会得到一个NPE。您也不需要进行所有导航(这看起来有点可疑,而且肯定会令人困惑)。试试这个:

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

【讨论】:

  • 这似乎有效,但为什么我不必直接从顶部 标记?
  • @DCSoftware - 因为您可以直接从文档根目录收集所有&lt;author&gt; 标签。当您为某个节点调用 getElementsByTagName 时,它会搜索以该节点为根的整个树,而不仅仅是子节点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多