Shpigford Shpigford - 1 year ago 95
Ruby Question

How do I convert a Ruby hash to XML?

Here is the specific XML I ultimately need:

<?xml version="1.0" encoding="UTF-8"?>

But say I have a controller (Ruby on Rails) that is sending the data to a method. I'd prefer to send it as a hash, like so:

:first_name => 'Joe',
:last_name => 'Blow',
:email => ''

So, how can I convert the hash to that XML format?

ry. ry.
Answer Source

ActiveSupport adds a to_xml method to Hash, so you can get pretty close to what you are looking for with this:

my_hash = { :first_name => 'Joe', :last_name => 'Blow', :email => ''}
my_hash.to_xml(:root => 'customer')

And end up with:

<?xml version="1.0" encoding="UTF-8"?>

Note that the underscores are converted to dashes.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download