KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > crazybob > rss > Parser


1 package org.crazybob.rss;
2
3 import org.jdom.*;
4 import org.jdom.input.*;
5 import java.io.*;
6 import java.util.*;
7
8 /**
9  * A very simple, liberal RSS XML parser.
10  *
11  * @author Bob Lee (crazybob@crazybob.org)
12  */

13 public class Parser {
14     
15     public Channel parse(Document document) {
16         // this code sucks, but it gets the job done...
17
Channel channel = new Channel();
18         Element rootElement = document.getRootElement();
19         Namespace namespace = rootElement.getNamespace();
20         Element channelElement = rootElement.getChild("channel");
21         Collection itemElements;
22         // not in default namespace, try another...
23
if (channelElement == null) {
24             // rdf -- these elements are in a different namespace...
25
namespace = Namespace.getNamespace("http://purl.org/rss/1.0/");
26             channelElement = rootElement.getChild("channel", namespace);
27             itemElements = rootElement.getChildren("item", namespace);
28         }
29         else {
30             itemElements = channelElement.getChildren("item");
31         }
32         channel.setTitle(channelElement.getChildText("title", namespace));
33         for (Iterator iterator = itemElements.iterator(); iterator.hasNext();) {
34             Element itemElement = (Element) iterator.next();
35             Item item = new Item();
36             item.setTitle(itemElement.getChildText("title", namespace));
37
38             String JavaDoc link = itemElement.getChildText("link", namespace);
39             if (link == null)
40                 link = itemElement.getChildText("guid", namespace);
41             item.setLink(link);
42
43             item.setDescription(
44                 itemElement.getChildText("description", namespace));
45             channel.getItems().add(item);
46         }
47         return channel;
48     }
49
50     public static void main(String JavaDoc[] args) throws Exception JavaDoc {
51         Document document = new SAXBuilder().build(
52                 new FileReader(args[0]));
53         Channel channel = new Parser().parse(document);
54         System.out.println(channel);
55     }
56 }
57
Popular Tags