我通過解析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;
}
}
你可以試着用調試器調試它,因爲當你返回值和調用者獲取值之間的值不應該改變。 – 2014-08-31 14:56:36