Convert XML to Ruby Hash with Attributes

Purpose:

Convert XML to ruby ​​Hash with all node and attribute values

What I have tried:

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

hash = Hash.from_xml(xml)

      

Now I am getting this hash

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

      

Note that the id attribute is not displayed on the first comment element.

How do I resolve this?

+3


source to share


2 answers


I found a solution here - it's a gem

gem 'cobravsmongoose', '~> 0.0.2'

      

Try it,



  hash =CobraVsMongoose.xml_to_hash(xml)

      

here is the result:

{"test"=>{"@id"=>"appears", "comment"=>[{"@id"=>"doesnt appear", "$"=>"it worked"}, {"$"=>"see!"}, {}]}}

      

0


source


XMLConverter Class Active Support Issue Add the following code to any initializer 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 give you the output as shown below.

Ex Input XML



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

Hash.from_xml(xml)

      

The output will be

{"album"=>{"song_name"=>{"type"=>"published", "__content__"=>"Do Re Mi"}}}

      

+1


source







All Articles