2010-10-15 26 views
5

Tôi nhìn rất nhiều tuts nhưng this một dường như đã đã cho tôi nơi tôiNokogiri XML Parsing với Rails

khiển

def index 
     require 'nokogiri' 
     doc = Nokogiri::XML(open("http://sports.yahoo.com/top/rss.xml")) 

     @links = doc.xpath('//item').map do |i| 
     {'title' => i.xpath('title'), 'link' => i.xpath('link'), 'description' => i.xpath('description')} 
     end 
    end 

xem

<ul> 
    <%= debug @links.each.first %> 
</ul> 

debug ra đưa

{"title"=>[#<Nokogiri::XML::Element:0x8199ce34 name="title" children=[#<Nokogiri::XML::Text:0x8199c6f0 "Kolb to get start for Eagles vs. Falcons (AP)">]>], "description"=>[#<Nokogiri::XML::Element:0x8199b660 name="description" children=[#<Nokogiri::XML::Text:0x8199a594 "Kevin Kolb will make his second straight start in place of the injured Michael Vick when the Philadelphia Eagles host Atlanta on Sunday. Eagles coach Andy Reid says Vick practiced Friday for the first time since sustaining a rib cartilage injury on Oct. 3. There's a chance Vick will be the backup quarterback against his former team.">]>], "link"=>[#<Nokogiri::XML::Element:0x81999f40 name="link" children=[#<Nokogiri::XML::Text:0x81999b58 "http://us.rd.yahoo.com/sports/rss/top/SIG=11npql9k5/*http%3A//sports.yahoo.com/nfl/news?slug=ap-eagles-qbs">]>]}

Điều tôi cần là lặp qua mảng liên kết và truy cập băm với tiêu đề và liên kết, nhưng tôi không biết cách thực hiện điều đó.

Trả lời

11

Nếu tôi hiểu chính xác, bạn chỉ cần lấy văn bản bên trong từ các nút xpath.

{'title' => i.xpath('title').inner_text, 
'link' => i.xpath('link').inner_text, 
'description' => i.xpath('description').inner_text 
} 

.......

+0

:) - đó là nó – s84

+0

Cảm ơn cho môi trường 'inner_text';) –

Các vấn đề liên quan