-3

我正在尝试从我在 java 中的 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

4

2 回答 2

2

问题是您的代码正在<author>使用 索引节点列表i,它计算<authors>标签的所有子节点,其中一些不是<author>元素。item(i)返回时,当null您尝试调用时,您会得到一个 NPE 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;
}
于 2013-04-09T16:30:32.507 回答
1

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

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

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

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

于 2013-04-09T16:31:31.087 回答