简体   繁体   English

如何将Ruby哈希转换为XML?

[英]How do I convert a Ruby hash to XML?

Here is the specific XML I ultimately need: 这是我最终需要的特定XML:

<?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. 但是说我有一个控制器( Ruby on Rails )将数据发送到方法。 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? 那么,我怎样才能将哈希转换为XML格式?

ActiveSupport adds a to_xml method to Hash, so you can get pretty close to what you are looking for with this: ActiveSupport为Hash添加了一个to_xml方法,因此您可以通过以下方式获得非常接近的内容:

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. 请注意,下划线将转换为破折号。

If this data is a model, look at overriding to_xml . 如果此数据是模型,请查看覆盖to_xml

Otherwise, Builder is a good option. 否则, Builder是个不错的选择。

我建议像XmlSimple这样的宝石提供这种设施。

Gem gyoku very nice. 宝石gyoku非常好。

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. 和更有用的选择。

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) 是幻灯片(有趣的部分从> =第37页开始)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM