import java.io.*;
import java.net.URL;
import java.util.List;
import java.util.Iterator;
import org.jdom.*;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;

/**
 * Basic JDOM Example
 * Outputs Top News Stories from Moreover.com
 * Example usage:
 * java news1
 */

public class news1 {

  // Download and Process XML File
  public void process (String url) {
    try {
      //  Use SAXBuilder
      SAXBuilder builder = new SAXBuilder();
      Document doc = builder.build(new URL(url));
      extractNewsStories (doc);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  //  Walk through JDOM Tree and extract all articles
  //  For each article, print article ID, headline text and source
  private void extractNewsStories (Document doc) {
    Element root = doc.getRootElement();
    //  Get all children named, "article"
    List articles = root.getChildren("article");
    Iterator i = articles.iterator();
    System.out.println("Number of Articles:  "+articles.size());
    while (i.hasNext()) {
      Element article = (Element) i.next();
      String articleID = article.getAttributeValue("id");
      Element headline = article.getChild("headline_text");
      String headlineText = headline.getText();
      //  Alternative, compact text is commented below
      //  headlineText = article.getChild("headline_text").getText();
      String source = article.getChild ("source").getText();
      String harvestTime = article.getChild ("harvest_time").getText();
      System.out.print (articleID+":  "+headlineText+" ("+source+":  ");
      System.out.println (harvestTime+")");
    }
  }

  public static void main (String[] args) {
    System.out.println ("Today's Top News Stories");
    news1 news = new news1();
    news.process("http://p.moreover.com/cgi-local/page?c=Top%20stories&o=xml");
  }

}
