将节点输入保存到字符串时遇到问题

时间:2013-09-27 14:56:17

标签: java xml parsing nodes getter-setter

以下是我为2课程设计的课程。基本上我想解析维基页面的标题,并将其保存到字符串标题或我可以使用类似retrieveTitle.setText(WikiSearcherExtension.title);之类的东西从另一个类调用它在eclipse中告诉我局部变量标题根本没有用到存储节点信息。

它不允许我将xml粘贴为代码块,所以这里是我一直使用的网址http://en.wikipedia.org/w/api.php?action=query&prop=revisions&format=xml&rvprop=timestamp&rvlimit=1&rvtoken=rollback&titles=test&redirects=

public class WikiParserTrials {

    private String wikiInformation;
    private String wikiUrl;
    String title;

    public void urlRefactor(String url) throws IOException {
        String wikiPageName = url.replaceAll(" ", "_");
        wikiUrl = "http://en.wikipedia.org/w/api.php?action=query&prop=revisions&format=xml&rvprop=timestamp&rvlimit=1&rvtoken=rollback&titles=test&redirects=";
        setUrlInformation();
    }

    private void setUrlInformation() throws IOException {
        URL url = new URL(wikiUrl);
        URLConnection connection = url.openConnection();
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

        wikiInformation = "";
        for (String line = reader.readLine(); line != null; line = reader.readLine()) {
            wikiInformation += line;
        }
    }

    public class ReadAndPrintXMLFile {

        public void main(String argv[]) {
            try {
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();
                InputSource is = new InputSource();
                is.setCharacterStream(new StringReader(wikiInformation));

                Document doc = db.parse(is);
                NodeList nodes = doc.getElementsByTagName("normalized");

                for (int i = 0; i < nodes.getLength(); i++) {
                    Element element = (Element) nodes.item(i);

                    NodeList name = element.getElementsByTagName("to");
                    Element line = (Element) name.item(0);
                    String title = (getCharacterDataFromElement(line));

                }

            } 
            catch (Throwable t) {
                t.printStackTrace();
            }
        }       
    }
}

3 个答案:

答案 0 :(得分:0)

在main方法中删除String之前的title。你正在覆盖全球的那个。

答案 1 :(得分:0)

之所以从未使用过,就像luiso1979所说的那样。你正在覆盖String。

String title;
String title = (getCharacterDataFromElement(line`));

你应该拥有的是

String title = "";
title = (getCharacterDataFromElement(line));

答案 2 :(得分:0)

您的属性titleString,并且在您的for句子中覆盖了该值(您应该像其他解决方案所说的那样修复),因此您只能获得最后一个节点的标题。我建议您使用其他数据结构,例如List<String> titles = = new ArrayList<String>();,并存储所有值titles.add(getCharacterDataFromElement(line));

相关问题