如何使用Nokogiri解析XML并拆分节点值?

时间:2011-12-21 02:16:22

标签: ruby-on-rails ruby xml xml-parsing nokogiri

我正在使用Nokogiri解析XML。

doc = Nokogiri::XML("http://www.enhancetv.com.au/tvguide/rss/melbournerss.php")

我不确定如何正确地检索节点值。

我特别关注位于title父节点下的linkdescriptionitem节点。

<item>
    <title>Toasted TV - TEN - 07:00:00 - 21/12/2011</title>
    <link>http://www.enhancetv.com.au/tvguide/</link>
    <description>Join the team for the latest in gaming, sport, gadgets, pop culture, movies, music and other seriously fun stuff! Featuring a variety of your favourite cartoons.</description>
</item>

我想做的是title.split("-")这样我就可以将日期和时间字符串转换为有效的DateTime对象,以便稍后在轨道上使用。

3 个答案:

答案 0 :(得分:3)

由于这是RSS提要,您可能需要考虑RSS解析器:

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

答案 1 :(得分:2)

对于您提到的示例标题字符串:

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

这会为您提供DateTime对象:Wed, 21 Dec 2011 07:00:00 +0000

但是你必须留意你可能需要处理的标题变化。修改分割以满足您的需要。

更新:没有注意到您还想了解有关如何解析文档的更多信息。所以这是如何:

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

这将加载数据数组中项目的所有标题,链接和描述。 Nokogiri :: XML接受一个字符串作为xml文档内容,因此您需要打开该URL然后将结果提供给它。

答案 2 :(得分:1)

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
}