rwi*_*ams 11
require 'active_support' #for to_xml() 'gem install activesupport' use the 2.3 branch
require 'json' #part of ruby 1.9 but otherwise 'gem install json'
my_json = "{\"test\":\"b\"}"
my_xml = JSON.parse(my_json).to_xml(:root => :my_root)
Run Code Online (Sandbox Code Playgroud)
另请注意to_xml的根参数.如果你没有指定一个root,那么它将使用'hash'这个词作为root,这看起来不是很好.
关于@rwilliams又名r-dub答案:
ActiveSupport将其组件移动到单独的模块中以实现粒度.我们可以告诉它只加载某些子集,或者,如果我们仍然选择,我们可以一次加载所有内容,而不是一次性加载所有内容.无论如何,我们不能require 'activesupport'像以前那样使用,而是我们必须使用require 'activesupport/all'或者其中一个子集.
>> require 'active_support/core_ext/array/conversions' #=> true
>> [{:a => 1, :b => 2}, {:c => 3}].to_xml
=> "<?xml version="1.0" encoding="UTF-8"?>\n<objects type="array">\n <objects a="1" b="2" type="hash"/>\n <objects c="3" type="hash"/>\n</objects>\n"
Run Code Online (Sandbox Code Playgroud)
此外,ActiveSupport包含JSON支持,因此您可以使用AR执行整个转换:
>> require 'active_support/all' #=> true
>> json = {'foo'=>'bar'}.to_json #=> "{"foo":"bar"}"
>> ActiveSupport::JSON.decode(json).to_xml #=> "<?xml version="1.0" encoding="UTF-8"?>\n<hash>\n <foo>bar</foo>\n</hash>\n"
Run Code Online (Sandbox Code Playgroud)
第一行加载XML和JSON转换.第二行设置用于测试的JSON示例.第三行采用伪装JSON,对其进行解码,然后将其转换为XML.