5

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 ?

2 Answers 2

3

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"}}}
Sign up to request clarification or add additional context in comments.

Comments

0

I found the solution here is the gem

gem 'cobravsmongoose', '~> 0.0.2'

Try this ,

  hash =CobraVsMongoose.xml_to_hash(xml)

here is result :

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.