1

I hope I can get the list of hashed like that.

Is there any gem can do me a favor ?

Expected result

[
    {
     "prog_name": "TAIWAN CTA Index",
     "prog_id": 9
    },
    {
     "prog_name": "CTO CTA Index",
     "prog_id": 12
    },    
]

Original input file source.xml

<prog>
  <prog_name>TAIWAN CTA Index</prog_name>
  <prog_id>9</prog_id>
</prog>
<prog>
  <prog_name>CTO CTA Index</prog_name>
  <prog_id>12</prog_id>
</prog>
...
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
user3675188
  • 7,271
  • 11
  • 40
  • 76
  • 1
    possible duplicate of [How do I convert XML into a hash in Rails?](http://stackoverflow.com/questions/4150856/how-do-i-convert-xml-into-a-hash-in-rails) – pangpang Sep 24 '15 at 07:53
  • Another possible duplicate: http://stackoverflow.com/questions/1230741/convert-a-nokogiri-document-to-a-ruby-hash/7488299#7488299 – nathanvda Sep 24 '15 at 11:13

1 Answers1

2

You should have a look at Nokogiri. Something like:

@doc = Nokogiri::XML(<IO thing here>)
@doc.xpath('prog').map do |prog_element| 
  {
    'prog_name' => prog_element.xpath('prog_name').content,
    'prog_id' => prog_element.xpath('prog_id').content
  }
end

would do it for you.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
froderik
  • 4,642
  • 3
  • 33
  • 43