Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert XML to ruby hash with attributes

Objective :

Convert XML to ruby Hash , with all node and attributes values

What i tried :

xml  = 
  '<test id="appears">
    <comment id="doesnt appear">
      it worked
    </comment>
    <comment>
     see!
    </comment>
    <comment />
  </test>'

hash = Hash.from_xml(xml)

Now i get this hash

#=>{"test"=>{"id"=>"appears", "comment"=>["it worked", "see!", nil]}}

Notice how the id attribute on the first comment element doesn't appear.

How to resolve this ?

like image 585
ramamoorthy_villi Avatar asked Oct 21 '22 00:10

ramamoorthy_villi


1 Answers

It's problem with active support XMLConverter class Please add following code to any of your initializers file.

module ActiveSupport
    class XMLConverter
        private
            def become_content?(value)
                value['type'] == 'file' || (value['__content__'] && (value.keys.size == 1 && value['__content__'].present?))
            end
    end
end

It will gives you output like following.

Ex Input XML

xml = '<album>
   <song-name type="published">Do Re Mi</song-name>
</album>'

Hash.from_xml(xml)

Output will be

{"album"=>{"song_name"=>{"type"=>"published", "__content__"=>"Do Re Mi"}}}
like image 194
KrunaL Avatar answered Oct 23 '22 03:10

KrunaL