gpt4 book ai didi

java - 无法从 try-catch 嵌套 for 循环中提取字符串

转载 作者:行者123 更新时间:2023-12-01 12:35:56 25 4
gpt4 key购买 nike

我正在解析 XML 文件以获取子节点,这确实有效。我只是想将其放入字符串中并将其传递出 for 循环,但是当我将其传递出去时,它不会将所有子节点放入字符串中,有时它不会在字符串中放入任何内容。如果它在 if 语句下使用 System.out.println(data) 那么它工作正常。我想从 if 循环中获取数据并将其传递。这是我的代码...

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;
}
}

最佳答案

我没有看到 try 语句与循环结合产生任何问题。但是,我不确定您的 getString 函数是否按照您想象的方式工作。仔细看赋值数据的语句:

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

对于循环中的每次迭代,数据变量都会完全重新分配。您的返回值将仅包含来自最后处理的节点的数据。

我认为您可能想要做的是将节点的值连接到字符串的末尾。你可以这样写:

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

关于java - 无法从 try-catch 嵌套 for 循环中提取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25593130/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com