代码之家  ›  专栏  ›  技术社区  ›  Sam å±±

nokogiri用rails进行XML解析

  •  5
  • Sam å±±  · 技术社区  · 15 年前

    我看了很多短裙,但是 this 似乎有人把我带到了现在的位置

    控制器

      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
    

    看法

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

    调试输出

    {"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">]>]}

    我需要的是循环访问链接数组,并使用标题和链接访问哈希,但我不知道如何这样做。

    1 回复  |  直到 14 年前
        1
  •  11
  •   Community Mohan Dere    14 年前

    如果我理解正确,您只需要从xpath节点获取内部文本。

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

    ……