Improved RSSLister

Print only item titles:

import org.xmlpull.v1.*;
import java.net.*;
import java.io.*;

 
public class BetterRSSLister {

  public static void main(String[] args) {
        
    if (args.length == 0) {
      System.err.println("Usage: java BetterRSSLister url" );
      return;   
    }
        
    try {
      XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
      XmlPullParser parser = factory.newPullParser();
      
      InputStream in;
      try {
        URL u = new URL(args[0]);
        in = u.openStream();
      }
      catch (MalformedURLException ex) {
          // Maybe it's a file name
          in = new FileInputStream(args[0]);
      }
      parser.setInput(in, null);
      
      boolean inItem = false;
      boolean inTitle = false;
      // Nested elements could be handled by incrementing
      // and decrementing an integer instead
      // of a simple boolean.
      while (true) {
         int event = parser.next();
         if (event == XmlPullParser.START_TAG) {
             String name = parser.getName();
             if (name.equals("title")) inTitle = true;
             if (name.equals("item")) inItem = true;
         }
         else if (event == XmlPullParser.END_TAG) {
             String name = parser.getName();
             if (name.equals("title")) inTitle = false;
             if (name.equals("item")) inItem = false;
         }
         else if (event == XmlPullParser.TEXT) {
             if (inTitle && inItem) System.out.println(parser.getText());
         }
         else if (event == XmlPullParser.END_DOCUMENT) {
             break;
         } // end else if
      }  // end while
    }
    catch (XmlPullParserException ex) {
       System.out.println(ex);  
    }
    catch (IOException ex) {
      System.out.println("IOException while parsing " + args[0]);   
    }
        
  }

}

Previous | Next | Top | Cafe con Leche

Copyright 2000-2002 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified November 21, 2002