Creating RSS using Java
I wanted to create RSS feeds for karensrecipes.com using Java. I did my ‘research‘, came to this page: Ben Hammersley.com: Java RSS libraries and then used the RSS4j library to create a servlet that serves up dynamic RSS feeds of the 10 most recently created recipes per category (samples: Breakfast, Soup, Barbeque..).
They syntax is pretty simple, you get an RssDocument and set which version you want to use (RSS 1.0, .9 or .91):
RssDocument doc = new RssDocument();
doc.setVersion(RssDocument.VERSION_10);
and then create a RssChannel object and add that to the RssDocument:
RssChannel channel = new RssChannel();
channel.setChannelTitle("Karens Recipes | Most Recent");
channel.setChannelLink("http://www.karensrecipes.com/3/Soup/default.jsp");
channel.setChannelDescription("The 10 most recently added recipes in the soup category.");
channel.setChannelUri("http://www.karensrecipes.com/rss/?categoryid=3");
doc.addChannel(channel);
Next, you’ll retrieve the items using a database, the file system, etc… and add each item as a RssChannelItem:
// connect to the datasource
// iterate over something (db? vector?...)
RssChannelItem item = new RssChannelItem();
item.setItemTitle(label);
item.setItemLink(link);
item.setItemDescription(description);
channel.addItem(item);
and then finally, using the RssGenerator class, call the generateRss() method, in this case I’m sending the output to a Servlet PrintWriter:
PrintWriter out = response.getWriter();
RssGenerator.generateRss(doc, out);
You could just as easily write it to a file:
File file = new File("/opt/data/rss.xml");
try{
RssGenerator.generateRss(doc, file);
System.out.println("RSS file written.");
}
catch(RssGenerationException e){
e.printStackTrace();
}
Simple. Easy to use.
5 Comments