Wednesday, 26 September 2012

How to read RSS Feed in Java ?

RSS have various full forms available online
  • Rich Site Summary (In RSS 0.91)
  • RDF Site Summary (Resource Description Framework Site Summary - In RSS 0.90, 1.0)
  • Reallty Simple Syndication (in RSS 2.0)

RSS is a standardized Web Feed Format
Web Feed is Data Format which provide frequent updated content
RSS provide frequent updated content such as Blog Entries, News Headlines, Audio, Video etc.
It is supported in all major consumer feed readers along with ATOM Feed reader which is alternative to RSS

Following example shows reading RSS Feed  from particular URL and make xml file at your local machine.

package ReadingRSS;

import java.io.*;
import java.net.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import org.w3c.dom.*;

public class ReadingRSS
{
    URL url = null;
    DocumentBuilder builder = null;
    TransformerFactory transformerFactory = null;
    Document objDocument = null;
    Transformer transformer = null;
    DOMSource DOMSource = null;
    StreamResult streamResult = null;

    public ReadingRSS() {
    }

    public boolean getFeedXML()
    {
        try
        {
            url = new URL("http://news.google.com/rss/");
            builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            objDocument = builder.parse(url.openStream());
            transformerFactory = TransformerFactory.newInstance();
            transformer = transformerFactory.newTransformer();
            DOMSource = new DOMSource(objDocument);
            streamResult = new StreamResult(new File("E:/GoogleFeed.xml"));
            transformer.transform(DOMSource, streamResult);
            return true;
        }
        catch (Exception exception)
        {
            System.out.println("Exception: " + exception);
        }
        return true;
    }
   
    public static void main(String[] clArgs)
    {
        ReadingRSS RSSReader = new ReadingRSS();
        if (RSSReader.getFeedXML())
            System.out.println("Feed Consumed");
        else
            System.out.println("Feed not Consumed");
    }
}


This code will directly Ping the URL mentioned in URL constructor and brings the source to your machine and generate a XML file on your local Machine

No comments:

Post a Comment