Reputation: 2055
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 ?
Upvotes: 5
Views: 1848
Reputation: 181
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"}}}
Upvotes: 3
Reputation: 2055
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!"}, {}]}}
Upvotes: 0