2015-08-21 3 views
0

Я следую за этим Youtube tutorial, но пока он получает ВСЕ заголовки из CNN RSS, я получаю только 1 заголовок. Почему это так?Java Читать RSS-канал

мой код (такой же, как тот, в учебнике, насколько я могу видеть)

import java.net.MalformedURLException; 
import java.net.URL; 
import java.io.*; 


public class ReadRSS { 

    public static void main(String[] args) { 

     System.out.println(readRSSFeed("http://rss.cnn.com/rss/edition.rss")); 
    } 

    public static String readRSSFeed(String urlAddress){ 
     try{ 
      URL rssUrl = new URL (urlAddress); 
      BufferedReader in = new BufferedReader(new InputStreamReader(rssUrl.openStream())); 
      String sourceCode = ""; 
      String line; 
      while((line=in.readLine())!=null){ 
       if(line.contains("<title>")){ 
        System.out.println(line); 
        int firstPos = line.indexOf("<title>"); 
        String temp = line.substring(firstPos); 
        temp=temp.replace("<title>",""); 
        int lastPos = temp.indexOf("</title>"); 
        temp = temp.substring(0,lastPos); 
        sourceCode +=temp+ "\n" ; 
       } 
      } 
      in.close(); 
      return sourceCode; 
     } catch (MalformedURLException ue){ 
      System.out.println("Malformed URL"); 
     } catch (IOException ioe){ 
      System.out.println("Something went wrong reading the contents"); 
     } 
     return null; 
    } 
} 

ответ

2

формат канала CNN изменился с тех пор он сделал, что Youtube видео. В коде делается предположение, что в каждой строке есть один тег заголовка, когда на самом деле их несколько. Что-то вроде этого должно работать сейчас:

while ((line = in.readLine()) != null) { 
    int titleEndIndex = 0; 
    int titleStartIndex = 0; 
    while (titleStartIndex >= 0) { 
     titleStartIndex = line.indexOf("<title>", titleEndIndex); 
     if (titleStartIndex >= 0) { 
      titleEndIndex = line.indexOf("</title>", titleStartIndex); 
      sourceCode += line.substring(titleStartIndex + "<title>".length(), titleEndIndex) + "\n"; 
     } 
    } 
} 
Смежные вопросы