一、准备工作
二、使用rome.jar解析rss文件
URL url = new URL("http://example.com/rss.xml");
SyndFeedInput input = new SyndFeedInput();
SyndFeed feed = input.build(new XmlReader(url));
// 获取RSS源文件的标题
String title = feed.getTitle();
// 获取所有items
List<SyndEntry> entries = feed.getEntries();
// 获取第一个item的标题
String entryTitle = entries.get(0).getTitle();
// 获取第一个item的URL地址
String entryUrl = entries.get(0).getLink();
三、使用jdom.jar解析rss文件
SAXBuilder builder = new SAXBuilder();
URL url = new URL("http://example.com/rss.xml");
Document doc = builder.build(url);
Element root = doc.getRootElement();
Element rss = root.getChild("rss");
Element channel = rss.getChild("channel");
// 获取RSS源文件的标题
String title = channel.getChildText("title");
// 获取所有items
List<Element> items = channel.getChildren("item");
// 获取第一个item的标题
String entryTitle = items.get(0).getChildText("title");
// 获取第一个item的URL地址
String entryUrl = items.get(0).getChildText("link");
示例一:
使用rome.jar获得掘金RSS源文件中的信息
import com.rometools.rome.io.SyndFeedInput;
import com.rometools.rome.io.XmlReader;
import com.rometools.rome.feed.synd.SyndFeed;
import com.rometools.rome.feed.synd.SyndEntry;
import java.net.URL;
import java.util.List;
public class RssExample{
public static void main(String[] args) {
try {
URL url = new URL("https://juejin.cn/rss");
SyndFeedInput input = new SyndFeedInput();
SyndFeed feed = input.build(new XmlReader(url));
String title = feed.getTitle();
List<SyndEntry> entries = feed.getEntries();
for (SyndEntry entry : entries) {
String entryTitle = entry.getTitle();
String entryUrl = entry.getLink();
System.out.println(entryTitle + " : " + entryUrl);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
示例二:
使用jdom.jar获得豆瓣读书RSS源文件中的信息
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import java.net.URL;
import java.util.List;
public class RssExample{
public static void main(String[] args) {
try {
SAXBuilder builder = new SAXBuilder();
URL url = new URL("https://book.douban.com/feed/review/book");
Document doc = builder.build(url);
Element root = doc.getRootElement();
Element rss = root.getChild("rss");
Element channel = rss.getChild("channel");
String title = channel.getChildText("title");
List<Element> items = channel.getChildren("item");
for (Element item : items) {
String entryTitle = item.getChildText("title");
String entryUrl = item.getChildText("guid");
System.out.println(entryTitle + " : " + entryUrl);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}