如今不少的新聞網站,博客網站等都提供了RSS訂閱功能,咱們能夠很方便的進行RSS訂閱,下面我使用rome-0.9.jar進行RSS訂閱,具體代碼以下:java
如訂閱網頁新聞,先要獲得該RSS訂閱的地址(xml頁面):http://news.163.com/special/00011K6L/rss_gn.xml;post
URL feedUrl = new URL("http://news.163.com/special/00011K6L/rss_gn.xml"); SyndFeedInput input = new SyndFeedInput(); SyndFeed feed = input.build(new XmlReader(feedUrl)); System.out.println(feed); //從feed中獲得entry List list = feed.getEntries(); for (int i=0; i< list.size(); i++) { SyndEntry entry = (SyndEntry)list.get(i); System.out.println("連接爲 = "+entry.getLink()); System.out.println("標題爲 = "+entry.getTitle()); System.out.println("時間爲 = "+entry.getPublishedDate()); System.out.println("內容爲 = "+entry.getDescription().getValue()); System.out.println("Categories爲 = "+entry.getCategories().get(0)); System.out.println("=============================================================================="); }
很是方便,一樣使用該包來建立RSS格式的xml進行訂閱操做也是很是方便的,下面進行示例:網站
package djn.test.rss.rome; import com.sun.syndication.feed.rss.*; import com.sun.syndication.io.FeedException; import com.sun.syndication.io.WireFeedOutput; import java.util.*; public class RssFeedFactory { public static void main(String [] args){ //新建Channel對象,對應rss中的<channel></channel> /* Channel對象有兩個構造器,一個默認的無參構造器用於clone對象, * 平時建立Channel對象時只能使用有參構造器Channel(String type) * 這個參數type很講究,起初我隨便填寫了一些字符串,都拋出異常,非法的type * 後來逼急了,上網把rome源碼搞下來,才搞明白type得是"rss_x.x"這樣的 * rome的文檔裏也沒有寫明,浪費了很多時間研究這個type究竟應該是什麼。 */ Channel channel = new Channel("rss_2.0"); channel.setTitle("Test RSS channel's title"); channel.setDescription("channel的描述"); channel.setLink("http://hi.baidu.com/openj/rss"); channel.setEncoding("GBK"); //這個list對應rss中的item列表 List items = new ArrayList(); //新建Item對象,對應rss中的<item></item> Item item = new Item(); item.setAuthor("item author jnduan"); item.setTitle("item title"); //新建一個Description,它是Item的描述部分 Description description = new Description(); description.setType("item description type"); description.setValue("item description value"); item.setDescription(description); items.add(item); channel.setItems(items); //用WireFeedOutput對象輸出rss文本 WireFeedOutput out = new WireFeedOutput(); try { System.out.println(out.outputString(channel)); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (FeedException e) { e.printStackTrace(); } } }
生成的RSS格式的xml
<?xml version="1.0" encoding="GBK"?>
<rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:taxo="http://purl.org/rss/1.0/modules/taxonomy/" version="2.0">
<channel>
<title>Test RSS channel's title</title>
<link>http://hi.baidu.com/openj/rss</link>
<description>channel的描述</description>
<item>
<title>item title</title>
<description>item description value</description>
<author>item author jnduan</author>
</item>
</channel>
</rss>
ui