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

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

问题描述

这是我最终需要的特定 XML:

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>

但假设我有一个控制器 (Ruby on Rails) 将数据发送到方法.我更愿意将它作为散列发送,如下所示:

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'

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

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

推荐答案

ActiveSupport 添加了一个 to_xml 方法到 Hash,这样你就可以非常接近你正在寻找的东西:

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')

最后是:

<?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天全站免登陆