[英]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. 请注意,下划线将转换为破折号。
我建议像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. 和更有用的选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.