如何将 Ruby 哈希转换为 XML?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1739905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:58:29  来源:igfitidea点击:

How do I convert a Ruby hash to XML?

ruby-on-railsxmlrubyhash

提问by Shpigford

Here is the specific XML I ultimately need:

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

<?xml version="1.0" encoding="UTF-8"?>
<customer>
  <email>[email protected]</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:

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

:first_name => 'Joe',
:last_name => 'Blow',
:email => '[email protected]'

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

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

回答by ry.

ActiveSupport adds a to_xmlmethod to Hash, so you can get pretty close to what you are looking for with this:

ActiveSupportto_xml向 Hash添加了一个方法,因此您可以非常接近您正在寻找的内容:

sudo gem install activesupport

require "active_support/core_ext"

my_hash = { :first_name => 'Joe', :last_name => 'Blow', :email => '[email protected]'}
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>[email protected]</email>
</customer>

Note that the underscores are converted to dashes.

请注意,下划线将转换为破折号。

回答by vk26

Gem gyokuvery nice.

Gem 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.

和更多有用的选项。

回答by Steve Madsen

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

如果此数据是模型,请查看覆盖to_xml.

Otherwise, Builderis a good option.

否则,Builder是一个不错的选择。

回答by plainprogrammer

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

我建议使用像XmlSimple这样的 gem ,它提供这种功能。

回答by Marc Seeger

I did a short presentation about exactly that topic at my university a while back. Hereare the slides (Interesting part starts at >= page 37)

不久前,我在我的大学就这个主题做了一个简短的演讲。 是幻灯片(有趣的部分从 >= 第 37 页开始)