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 ?
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"}}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With