有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java无法从trycatch嵌套for循环中提取字符串

我正在解析一个XML文件以获取子节点,这确实有效。我只是想把它放到一个字符串中,然后把它从for循环中传递出去,但是当我把它传递出去时,它并没有把所有的子节点都放到字符串中,有时它什么也没有放到字符串中。如果它使用系统。出来如果在if语句下输入println(数据),那么它工作正常。我想从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;
    }
}

共 (2) 个答案

  1. # 1 楼答案

    您应该在try块外定义b

        String b = null;
        try {
            Document doc = four.doIt();
            b = four.getString(doc);
    
            System.out.println(b);
        } catch (Exception e) {
            e.printStackTrace();
        }
    

    这将允许您在try块之外使用它的值

  2. # 2 楼答案

    我看不出try语句与循环组合会产生任何问题。但是,我不确定getString函数是否按照您认为的方式工作。仔细查看分配数据的语句:

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

    对于循环中的每个迭代,数据变量都被完全重新分配。您的返回值将只包含上次处理的节点的数据

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

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