用到的jar包为jdom.jar, rome-1.0.jar(https://rome.dev.java.net/dist/rome-1.0.jar)
package com.gary.util.rss;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.List;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;
/**
* RSS/Atom
* 支持从文件或URL读取
* @author gary
*
*/
public class FeedReader {
public static void main(String[] args) {
String source = "http://www.oschina.net/project/rss";
// String source = "rss_local_example.xml";
try {
//输出发布日期,链接,标题等内容,可自定义
String[] outputContent = {"publishedDate","link","title"};
print(read(source).getEntries(), outputContent);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (FeedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
/**
* 输出
* @param entries 内容
* @param args 要输出的列名称
* @throws SecurityException
* @throws NoSuchMethodException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static void print(List<SyndEntry> entries, String[] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException{
for (int i = 0; i < entries.size(); i++) {
SyndEntry entry = (SyndEntry) entries.get(i);
Object o = entry;
Class<? extends Object> cls = o.getClass();
Method m = null;
for (int j = 0; j < args.length; j++) {
String methodName = "get" + args[j].substring(0,1).toUpperCase() + args[j].substring(1);
m=cls.getMethod(methodName, (Class<?>[])null);
System.out.println(args[j]+":"+m.invoke(o, (Object[])null));
}
System.out.println("==========================================");
}
}
/**
* 读取
* @param source 目标
* @return
* @throws IOException
* @throws FeedException
* @throws IllegalArgumentException
*/
public static SyndFeed read(String source) throws IllegalArgumentException, FeedException, IOException{
//SyndFeedInput:从远程读到xml结构的内容转成SyndFeedImpl实例
SyndFeedInput input = new SyndFeedInput();
SyndFeed feed = null;
if(source.startsWith("http")){
URL feedUrl = new URL(source);
//rome按SyndFeed类型生成rss和atom的实例,
//SyndFeed是rss和atom实现类SyndFeedImpl的接口
feed = input.build(new XmlReader(feedUrl));
}else{
File feedUrl = new File(source);
feed = input.build(new XmlReader(feedUrl));
}
return feed;
}
}