如何将Ruby哈希转换为XML? [英] How do I convert a Ruby hash to XML?

查看:110
本文介绍了如何将Ruby哈希转换为XML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

但是说我有一个控制器( Ruby on Rails )将数据发送给一个方法。我宁愿将它作为散列发送,如下所示:

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

那么,如何将哈希转换为该XML格式?

解决方案

ActiveSupport为Hash添加了一个 to_xml 方法,接近你要找的东西:

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

结束于:

 <?xml version =1.0encoding =UTF-8? > 
< customer>
< last-name> Blow< / last-name>
< first-name> Joe< / first-name>
< email> joe@example.com< / email>
< / 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 sending 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:

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.

这篇关于如何将Ruby哈希转换为XML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆