views:

442

answers:

4

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 (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?

+1  A: 

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

Otherwise, Builder is a good option.

Steve Madsen
Well, I've tried to_xml and it's adding a <hash> tag around my XML. ie. <hash> <customer> ... </customer> </hash>
Shpigford
Is your customer hash an active record object?
bensie
Check out http://api.rubyonrails.org/classes/ActiveRecord/Serialization.html#M001876 for info on overriding how you want your XML structured.
bensie
+1  A: 

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

James Thompson
+8  A: 

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 => '[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.

ry
Ah nice, the root option was what was throwing me off. Thanks!
Shpigford
+1  A: 

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)

Marc Seeger