Convert REXML document records into a Hash
- Retrieve a single record -
1 h1 = doc.record('records/caller')
=> {"name"=>"Parents at the Doorphone", "caller_id"=>"doorphone2", "audio_file"=>"parents-doorphone.ogg"}
- Retrieve many records
1 h1 = doc.records('records/caller')
=> [{"name"=>"parents", "caller_id"=>"54768002343", "audio_file"=>"parents.ogg"}, {"name"=>"unknown", "caller_id"=>"", "audio_file"=>"unknown_caller.ogg"}, {"name"=>"Doorphone", "caller_id"=>"Doorphone", "audio_file"=>"someone-doorphone.ogg"}, {"name"=>"Anonymous", "caller_id"=>"Anonymous", "audio_file"=>"anonymous_caller.ogg"}, {"name"=>"E61", "caller_id"=>"21384757396", "audio_file"=>"my-e61-caller.ogg"}, {"name"=>"6600", "caller_id"=>"87662383483", "audio_file"=>"my-6600-caller.ogg"}, {"name"=>"Doorphone", "caller_id"=>"doorphone", "audio_file"=>"someone-doorphone.ogg"}, {"name"=>"Parents at the Doorphone", "caller_id"=>"doorphone2", "audio_file"=>"parents-doorphone.ogg"}]
Here's the code which extends the REXML class and the Array class
1 2 # convert an array into a hash 3 class Array 4 def to_h 5 Hash[*self] 6 end 7 end 8 9 class REXML::Document 10 11 def record(xpath) 12 self.root.elements.each(xpath + '/*'){}.inject([]) do |r,node| 13 r << node.name.to_s << node.text.to_s 14 end.to_h 15 end 16 17 def records(xpath) 18 self.root.elements.each(xpath){}.map do |row| 19 row.elements.each{}.inject([]) do |r,node| 20 r << node.name.to_s << node.text.to_s 21 end.to_h 22 end 23 end 24 25 end