且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将Ruby哈希转换为XML?

更新时间:2023-02-14 13:53:19

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? &GT; 
< 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.