2014-08-31 66 views
0

我通過解析XML文件來獲取可以工作的子節點。我只是想把它放到一個String中,並將其從for循環中傳出,但是當它將它傳遞出去時,它不會將所有子節點都放入String中,有時它不會將任何內容放入String中。如果它在if語句下使用System.out.println(data),那麼它工作正常。我想從if循環中獲取數據並將其傳遞。這裏是我的代碼...無法從try-catch嵌套for循環中提取字符串

public class Four { 

    public static void main(String[] args) { 

     Four four = new Four(); 
     String a = null; 
     try { 
      Document doc = four.doIt(); 
      String b = four.getString(doc); 

      System.out.println(b); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

    } 

    public Document doIt() throws IOException, SAXException, ParserConfigurationException { 
     String rawData = null; 

     URL url = new URL("http://feeds.cdnak.neulion.com/fs/nhl/mobile/feeds/data/20140401.xml"); 
     URLConnection connection = url.openConnection(); 
     InputStream is = connection.getInputStream(); 
     Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is); 

     return doc; 
    } 

    public String getString(Document doc) { 
     String data = null; 

     NodeList cd = doc.getDocumentElement().getElementsByTagName("game"); 
     for (int i = 0; i < cd.getLength(); i++) { 
      Node item = cd.item(i); 
      System.out.println("==== " + item.getNodeName() + " ===="); 
      NodeList children = item.getChildNodes(); 
      for (int j = 0; j < children.getLength(); j++) { 
      Node child = children.item(j); 


      if (child.getNodeType() != Node.TEXT_NODE) { 
       data = child.getNodeName().toString() + ":" + child.getTextContent().toString();  
       // if I System.out.println(data) here, it shows all everything 
       I want, when I return data it shows nothing but ===game=== 
      } 
     } 
     } 
     return data; 
    } 
} 
+0

你可以試着用調試器調試它,因爲當你返回值和調用者獲取值之間的值不應該改變。 – 2014-08-31 14:56:36

回答

1

我沒有看到try語句與循環結合產生的任何問題。但是,我不確定你的getString函數是否按照你認爲的方式工作。仔細查看分配數據的語句:

data = child.getNodeName().toString() + ":" + child.getTextContent().toString();  

對於循環中的每次迭代,都會完全重新分配數據變量。您的返回值僅包含來自最後一個已處理節點的數據。

我想你可能打算做的是將節點的值連接到你的字符串的末尾。你可以這樣寫:

data += "|" + child.getNodeName().toString() + ":" + child.getTextContent().toString(); 
0

你應該定義btry塊之外:

String b = null; 
    try { 
     Document doc = four.doIt(); 
     b = four.getString(doc); 

     System.out.println(b); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

這將讓你使用它的try塊之外的價值。