最近想用Rails写一个类似lilina的东东,搜集了关于用Ruby解析及创建RSS的一些资源,原来Ruby自带了一个RSS解析器和生成器,这给我们带来了极大的方便。
Ruby RSS 解析
ruby 代码
- require 'rss/1.0'
- require 'rss/2.0'
- require 'open-uri'
- feed= "http://www.iteye.com/blog/rss_blog/41837" # url或本地XML文件
- content = ""
- open(feed) do |s|
- content = s.read
- end
- rss = RSS::Parser.parse(content, false) # false表示不验证feed的合法性
上面的代码会将feed中的XML下载并解析,解析后的内容保存在对象rss中,下面我们来操作该对象。
ruby 代码
- channel = rss.channel
- items = rss.items # rss.channel.items亦可
- puts "频道信息"
- puts "标题: #{channel.title}"
- puts "链接: #{channel.link}"
- puts "描述: #{channel.description}"
- puts "更新时间: #{channel.date}"
- puts "文章数量: #{items.size}"
- for i in 0 ... items.size
- puts "----------- 文章#{i} -----------"
- puts "\t标题: #{items[i].title}"
- puts "\t链接: #{items[i].link}"
- puts "\t发表时间: #{items[i].date}"
- puts "\t内容: #{items[i].description}"
- end
对于RSS中channel和item的其它api操作,可以参照RSS的中文规范。
如果觉得上面的内容包含了太多的HTML字符,不方便查看的话,可以调用下面的to_html方法,将返回结果显示在view中。
ruby 代码
- class RSS::Rss
- def to_html
- max_description_length = 100
- html = "<h4><a href='#{channel.link}'>#{channel.title}</a></h4>"
- html << "<small>Updated on #{channel.date.strftime('%m/%d/%Y')}</small>" \
- if channel.date
- html << "<p>#{channel.description}</p>"
- html << "<ol>"
- channel.items.each do |i|
- html << "<li><strong><a href='#{i.link}'>#{i.title}</a></strong><br/>"
- html << "<small>Added on #{i.date.strftime("%m/%d/%Y")} at \
- #{i.date.strftime("%I:%M%p")}</small><br/>" if i.date
- desc_text = i.description.gsub(/<[^>]+>/,"").squeeze(" ").strip
- if desc_text.length > max_description_length
- desc_text = desc_text[0,max_description_length] + "…"
- else
- desc_text = i.description
- end
- html << "#{desc_text}"
- html << "</li>"
- end
- html << "</ol>"
- html
- end
- end
Ruby RSS 创建
创建RSS也非常容易,代码如下:
ruby 代码
"2.0" # ["0.9", "1.0", "2.0"] destination = "rss_cpc.xml" content = RSS::Maker.make(version) do |m| m.channel.title = "使用Ruby解析及创建RSS" m.channel.link = "http://cpccai.iteye.com" m.channel.description = "使用Ruby解析及创建RSS" m.items.do_sort = true # 文章按日期排序 i = m.items.new_item i.title = "使用Ruby解析RSS" i.link = "http://cpccai.iteye.com/blog/137941" i.date = Time.parse("2007/11/01 11:01") i = m.items.new_item i.title = "使用Ruby创建RSS" i.link = "http://cpccai.iteye.com/blog/137941" i.date = Time.now end File.open(destination,"w") do |f| f.write(content) end
require 'rss/maker' version =
运行后可以在文件所在目录找到生成的rss_cpc.xml文件。
参考文献:
1. Ruby RSS - Eating feeds tastefully
2. RSS教程 RSS基础知识及相关规范介绍
3. Ruby RSS相关网络资源 http://directory.fsf.org/project/rubyrss/ http://rubyforge.org/frs/?group_id=1624