簡體   English   中英

如何使用Nokogiri解析XML並拆分節點值?

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

我正在使用Nokogiri解析XML。

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

我不確定如何正確地正確檢索節點值。

我緊追在titlelinkdescription節點之后,它們位於item父節點下。

<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對象,以便以后在軌道上使用。

由於這是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

對於您提到的示例標題字符串:

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,然后將結果提供給它。

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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM