How do I parse XML using Nokogiri and split a node value?

半城伤御伤魂 提交于 2019-12-06 15:27:45

Since this is an RSS feed, you may want to consider an RSS parser:

require 'simple-rss'
require 'open-uri'

feed = 'http://www.enhancetv.com.au/tvguide/rss/melbournerss.php'
rss = SimpleRSS.parse open(feed)

rss.items.each do |item|
  puts item.title, item.link, item.description
end

For the example title string you mentioned:

DateTime.parse(s.split(" - ")[-2..-1].join(" "))

This gets you a DateTime object: Wed, 21 Dec 2011 07:00:00 +0000

But you have to keep an eye on the title variations you might need to deal with. Modify the split a bit to meet your need.

Update: didn't noticed you also want more info on how to parse the document. So here's how:

doc = Nokogiri::XML(open("http://www.enhancetv.com.au/tvguide/rss/melbournerss.php"))
data = doc.xpath("//item").map do |item|
  [
    item.search("title").first.content,
    item.search("link").first.content,
    item.search("description").first.content
  ]
end

This will load all title, link and description for items in the data array. Nokogiri::XML accepts a string as xml document content, so you need to open the url then feed the result to it.

def parse_time(text)
   items = text.split("-")
   DateTime.strptime("#{items[-2].strip}#{items[-1].strip}", "%H:%M:%S%d/%m/%Y")
end

content = Net::HTTP.get(URI.parse("http://www.enhancetv.com.au/tvguide/rss/melbournerss.php"))
doc = Nokogiri::XML(content){|config| config.noblanks }

doc.search("//item").map{ |node|
   node.children.inject({}) do |hash, node|
     if node.name == "title"
       #or another name
       hash["created_at"] = parse_time(node.text)
     end

     hash[node.name] =  node.text
     hash
   end
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!