Java 无法从循环的try-catch嵌套中提取字符串
我正在解析一个XML文件以获取子节点,这确实有效。我只是想把它放到一个字符串中,然后把它从for循环中传递出去,但是当我把它传递出去时,它并没有把所有的子节点都放到字符串中,有时它什么也没有放到字符串中。如果它在If语句下使用System.out.println(数据)in,那么它可以正常工作。我想从if循环中获取数据并将其传递。这是我的密码Java 无法从循环的try-catch嵌套中提取字符串,java,string,xml-parsing,try-catch,nodes,Java,String,Xml Parsing,Try Catch,Nodes,我正在解析一个XML文件以获取子节点,这确实有效。我只是想把它放到一个字符串中,然后把它从for循环中传递出去,但是当我把它传递出去时,它并没有把所有的子节点都放到字符串中,有时它什么也没有放到字符串中。如果它在If语句下使用System.out.println(数据)in,那么它可以正常工作。我想从if循环中获取数据并将其传递。这是我的密码 public class Four { public static void main(String[] args) { Fo
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;
}
}
公共四级{
公共静态void main(字符串[]args){
四个四=新的四个();
字符串a=null;
试一试{
Document doc=four.doIt();
字符串b=4.getString(doc);
系统输出打印ln(b);
}捕获(例外e){
e、 printStackTrace();
}
}
公共文档doIt()引发IOException、SAXException、ParserConfiguration异常{
字符串rawData=null;
URL=新URL(“http://feeds.cdnak.neulion.com/fs/nhl/mobile/feeds/data/20140401.xml");
URLConnection=url.openConnection();
InputStream is=connection.getInputStream();
Document doc=DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);
退货单;
}
公共字符串getString(文档文档){
字符串数据=null;
NodeList cd=doc.getDocumentElement().getElementsByTagName(“游戏”);
对于(int i=0;i
您应该在try
块之外定义b
:
String b = null;
try {
Document doc = four.doIt();
b = four.getString(doc);
System.out.println(b);
} catch (Exception e) {
e.printStackTrace();
}
这将允许您在
try
块之外使用它的值。我看不出try语句与循环组合会产生任何问题。但是,我不确定getString函数是否按照您认为的方式工作。仔细查看分配数据的语句:
data = child.getNodeName().toString() + ":" + child.getTextContent().toString();
对于循环中的每个迭代,数据变量都被完全重新分配。您的返回值将只包含上次处理的节点的数据
我认为您可能想做的是将节点的值连接到字符串的末尾。你可以这样写:
data += "|" + child.getNodeName().toString() + ":" + child.getTextContent().toString();
您是否可以尝试使用调试器对其进行调试,因为在返回值和调用者获取值之间,值不应更改。