Nokogiri解析 [英] Nokogiri parsing

查看:81
本文介绍了Nokogiri解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些XML:

xml = <<-EOT
<xml>
    <advcampaign_categories>
        <category id="85">Sport</category>
        <category id="79">Mobile</category>
        <category id="62">Flowers</category>
    </advcampaign_categories>
</xml>
EOT

并想解析它:

id=[]
text=[]
doc = Nokogiri::XML(xml)
doc.search('advcampaign_categories').each do |cat|
  c = cat.at('category')
  text << c.text
  id << c['id']    
end
h = Hash[text.zip id]

我的目标是获取像{sport:85, mobile:79..etc}这样的哈希.

My goal is get a hash like {sport:85, mobile:79..etc}.

此代码的问题是它仅返回一个元素sport:85.

The problem with this code is it only returns ONE element sport:85.

有什么建议吗?

推荐答案

require 'nokogiri'

doc = Nokogiri::XML.parse <<-EOT
<xml>
    <advcampaign_categories>
        <category id="85">Sport</category>
        <category id="79">Mobile</category>
        <category id="62">Flowers</category>
    </advcampaign_categories>
</xml>
EOT

# if you are >= 2.1
doc.css('category').map { |node| [node.text, node['id'].to_i] }.to_h
# => {"Sport"=>85, "Mobile"=>79, "Flowers"=>62}
# if you are below version < 2.1
Hash[doc.css('category').map { |node| [node.text, node['id'].to_i] }]
# => {"Sport"=>85, "Mobile"=>79, "Flowers"=>62}

这篇关于Nokogiri解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆