Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a Ruby hash to XML?

Here is the specific XML I ultimately need:

<?xml version="1.0" encoding="UTF-8"?>
<customer>
  <email>[email protected]</email>
  <first_name>Joe</first_name>
  <last_name>Blow</last_name>
</customer>

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 => '[email protected]'

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

like image 556
Shpigford Avatar asked Nov 16 '09 03:11

Shpigford


5 Answers

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

sudo gem install activesupport

require "active_support/core_ext"

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

And end up with:

<?xml version="1.0" encoding="UTF-8"?>
<customer>  
   <last-name>Blow</last-name>  
   <first-name>Joe</first-name>  
   <email>[email protected]</email>
</customer>

Note that the underscores are converted to dashes.

like image 83
ry. Avatar answered Oct 12 '22 02:10

ry.


Gem gyoku very nice.

Gyoku.xml(:lower_camel_case => "key")    
# => "<lowerCamelCase>key</lowerCamelCase>"

Gyoku.xml({ :camel_case => "key" }, { :key_converter => :camelcase })
# => "<CamelCase>key</CamelCase>"

Gyoku.xml({ acronym_abc: "value" }, key_converter: lambda { |key| key.camelize(:lower) })
# => "<acronymABC>value</acronymABC>"

and more useful options.

like image 29
vk26 Avatar answered Oct 12 '22 02:10

vk26


If this data is a model, look at overriding to_xml.

Otherwise, Builder is a good option.

like image 25
Steve Madsen Avatar answered Oct 12 '22 04:10

Steve Madsen


I would suggest a gem like XmlSimple which provides this kind of facility.

like image 41
plainprogrammer Avatar answered Oct 12 '22 03:10

plainprogrammer


I did a short presentation about exactly that topic at my university a while back. Here are the slides (Interesting part starts at >= page 37)

like image 23
Marc Seeger Avatar answered Oct 12 '22 02:10

Marc Seeger