我通过解析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