如何将 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
How do I convert a Ruby hash to XML?
提问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.
和更多有用的选项。

