Java RSS Reader Example

Posted by Tully on Mon 07 November 2011

Today I was working with the DOM in Java and decided to write a simple RSS reader. The code below is an example of a Java RSS Reader. You just give it an instance of URL through the setURL assessor. Then call the writeFeed() method which outputs the title/description/link of each item in the feed.

import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class RSSReader {

    private static RSSReader instance = null;

    private URL rssURL;

    private RSSReader() {}

    public static RSSReader getInstance() {
        if (instance == null)
            instance = new RSSReader();
        return instance;
    }

    public void setURL(URL url) {
        rssURL = url;
    }

    public void writeFeed() {
        try {
            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document doc = builder.parse(rssURL.openStream());

            NodeList items = doc.getElementsByTagName("item");

            for (int i = 0; i < items.getLength(); i++) {
                Element item = (Element)items.item(i);
                System.out.println(getValue(item, "title"));
                System.out.println(getValue(item, "description"));
                System.out.println(getValue(item, "link"));
                System.out.println();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getValue(Element parent, String nodeName) {
        return parent.getElementsByTagName(nodeName).item(0).getFirstChild().getNodeValue();
    }

    public static void main(String[] args) {
        try {
            RSSReader reader = RSSReader.getInstance();
            reader.setURL(new URL("http://www.tullyrankin.com/feed/rss"));
            reader.writeFeed();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}