2014-08-31 63 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块之外的价值。