2013-04-09 57 views
-3
讀取XML時

我試圖從這裏賈烏德我的XML文件中獲取的所有作者是XML代碼空指針在Java中

<?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

+1

完整的堆棧跟蹤在哪裏? – BobTheBuilder 2013-04-09 16:17:11

+0

'嘗試.. catch' - >堆棧跟蹤? – 2013-04-09 16:17:12

+2

這是XMLHandler.java的第73行嗎? – 2013-04-09 16:20:52

回答

1

的問題是,你的代碼索引<author>節點列表使用i,其中計數<authors>標記的所有孩子,其中一些不是<author>元素。當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; 
} 
+0

這似乎是工作,但爲什麼我不必從頂部標籤直接? – DCSoftware 2013-04-09 16:41:13

+0

@DCSoftware - 因爲您可以直接從文檔根目錄收集所有''標籤。當您爲節點調用'getElementsByTagName'時,它將搜索以該節點爲根的整個樹,而不僅僅是子節點。 – 2013-04-09 16:53:21

1

要找到一個顯示java.lang.NullPointerException的原因把一個斷點異常發生,在這種情況下,73線,並調查該行的變量。

我的猜測是,在你的代碼行:

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

變量eauthor元素,因此爲什麼e.getElementsByTagName("author")返回null

+0

如果'e'下沒有''節點,'getElementsByTagName'不會返回'null';它會返回一個空的'NodeList'。問題是如果'i'超出範圍,'item(i)'返回'null'。 – 2013-04-09 16:57:15

+0

當然,我認爲結果是,原始代碼是一團糟,你的清理版本是需要的。 – 2013-04-10 09:12:39