Katya
Katya

Reputation: 138

Nokogiri parsing

I have some 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

and want parse it:

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]

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

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

Any suggestions?

Upvotes: 0

Views: 105

Answers (1)

Arup Rakshit
Arup Rakshit

Reputation: 118299

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}

Upvotes: 4

Related Questions