开发者

How do I convert a Ruby hash to XML?

开发者 https://www.devze.com 2022-12-11 06:58 出处:网络
Here is the specific XML I ultimately need: <?xml version=\"1.0\" encoding=\"UTF-8\"?> <customer>

Here is the specific XML I ultimately need:

<?xml version="1.0" encoding="UTF-8"?>
<customer>
  <email>joe@example.com</email>
  <first_name>Joe</first_name>
  <last_name>Blow</last_name>
</customer>

But say I have a controller (Ruby on Rails) that is send开发者_如何学编程ing the data to a method. I'd prefer to send it as a hash, like so:

:first_name => 'Joe',
:last_name => 'Blow',
:email => 'joe@example.com'

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


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 => 'joe@example.com'}
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>joe@example.com</email>
</customer>

Note that the underscores are converted to dashes.


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.


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

Otherwise, Builder is a good option.


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


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)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号