2014-11-06 178 views
0

我有一些XML:引入nokogiri解析

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}哈希值。

該代碼的問題是它只返回一個元素sport:85

有什麼建議嗎?

+0

只有一個'advcampaign_categories',這就是爲什麼你只得到一個結果。將它改爲'doc.search('category).each'代替 – 2014-11-06 17:32:46

回答

4
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} 
+0

不錯的一行代碼;) – 2014-11-06 17:35:36