Thursday, December 2, 2010

Parse an RSS feed using Java



Here is a quick example of how to parse an RSS feed in Java. It may come handy when doing Android or Web apps.
The following example is being implemented as an static method in a console application; however, for a real project you may want to create a set of classes to provide a more OO approach.

private static void Rss(String feed) throws ParserConfigurationException,IOException, SAXException{

              URL url = new URL(feed);
              HttpURLConnection conn = (HttpURLConnection) url.openConnection();
              if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
                    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                    DocumentBuilder db = dbf.newDocumentBuilder();
                    Document doc;
                    doc = db.parse(url.openStream());
                    doc.getDocumentElement().normalize();
                    NodeList itemLst = doc.getElementsByTagName("item");
                   
                    for(int i=0; i < itemLst.getLength(); i++){
                         
                          Node item = itemLst.item(i);
                          if(item.getNodeType() == Node.ELEMENT_NODE){
                                Element ielem = (Element)item;
                                NodeList title = ielem.getElementsByTagName("title");
                                NodeList link = ielem.getElementsByTagName("link");
                                NodeList description = ielem.getElementsByTagName("description"); 
                                                              
                                System.out.print(title.item(0).getChildNodes().item(0).getNodeValue());
                                System.out.print("\t\n");
                                System.out.print(link.item(0).getChildNodes().item(0).getNodeValue());
                                System.out.print("\t\n");
                                System.out.print("\t\n");
                          }
                         
                    }
              }

 }

Usage:
Rss(“http://rss.cnn.com/rss/cnn_topstories.rss“);

Output:
Clinton hits phone to patch relations    
http://rss.cnn.com/~r/rss/cnn_topstories/~3/VBH1WQQ1mAI/index.html     
     
The secret life of Julian Assange  
http://rss.cnn.com/~r/rss/cnn_topstories/~3/4gGd2WPMSaE/index.html     
     
House to vote on Bush tax cuts     
http://rss.cnn.com/~r/rss/cnn_topstories/~3/c2AgZMKetoo/index.html

No comments:

Post a Comment