Jsoup错误的循环解析

时间:2013-03-28 12:03:01

标签: android parsing jsoup

需要解析一些文本并将它们放在列表中。我喜欢这个:

try {
            Document doc = Jsoup.connect(URL).get();

            Elements main = doc.select("div.day");
            for (i = 0; i < main.size(); i++) {
                Element m = main.get(i);

                Elements date = m.select("h2");
                for (j = 0; j < date.size(); j++) {
                    Element m1 = date.get(j);
                    dates = m1.select("a").attr("href");    
                }

                Elements titles = m.select("div.ep_box");
                for (k = 0; k < titles.size(); k++) {
                    Element tts = titles.get(k);
                    title = tts.select("h3 a[href]").text();  // titles
                    time = tts.select("small").text();  // time 
                    url = tts.select("h3 a").attr("href"); // links

                    if (title.contains(inputSearch)) {  // search type
                        Order o = new Order();
                        o.setTextName(title);
                        o.setTextEpisode(time);
                        o.setTextDate(dates);
                        o.setDetailsUrl(url);
                        listItems.add(o);   

System.out.println("Title: " + title + "\n" + "Time: " + time + "\n" + "Link: " + url + "\n" + "========================");
                    } 
                }
            }               

        }

在日志中,它完美无缺:

03-28 17:50:29.421: I/System.out(13409): Title: Naruto SD: Rock Lee no Seishun Full-Power Ninden
03-28 17:50:29.421: I/System.out(13409): Time: Ep: 48 (17:30) - TV Tokyo
03-28 17:50:29.421: I/System.out(13409): Link: /show/601/Naruto_SD%3A_Rock_Lee_no_Seishun_Full-Power_Ninden
03-28 17:50:29.421: I/System.out(13409): ========================
03-28 17:50:29.449: I/System.out(13409): Title: Naruto Shippuuden
03-28 17:50:29.449: I/System.out(13409): Time: Ep: 303 (19:30) - TV Tokyo
03-28 17:50:29.449: I/System.out(13409): Link: /show/18/Naruto_Shippuuden

但是在列表中的模拟器中仅显示最后的标题,时间和链接。我怎么能解决它? 感谢

1 个答案:

答案 0 :(得分:0)

我认为问题出在object o上。 我认为你必须为你的循环中的每个新元素创建它:

 Order o = new Order();
 o.setTextName(title);
 o.setTextEpisode(time);
 o.setTextDate(dates);
 o.setDetailsUrl(url);
 listItems.add(o);

否则你随每次迭代改变对象o的相同引用,这就是你只得到一个列表项的原因。