2010-11-24 61 views

回答

10
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) 

還要注意to_xml根的說法。如果你沒有指定一個根目錄,它會使用'hash'這個詞作爲根,這看起來不是很好。

-1

我不知道一個神奇的寶石來做它,但你可以輕鬆做到的是xml哈希和哈希到json。

require 'active_support' 
my_hash = Hash.from_xml(my_xml) 

然後

require 'json' 
my_json = my_hash.to_json 
+3

我想將JSON轉換爲XML,而不是XML到JSON – 2010-11-24 23:21:20

+0

無論如何,這些奇怪的引號是否正常工作?這看起來不太健康。 – jwueller 2010-11-24 23:25:12

6

關於@rwilliams又名R-配音答案:

ActiveSupport moved its components成粒度單獨的模塊。我們可以告訴它只加載特定的子集,或者如果我們仍然選擇,我們可以一次加載所有內容,而不是一次加載所有內容。無論如何,我們不能像以前那樣使用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" 

此外,包含的ActiveSupport JSON支持,這樣你就可以做AR整個轉換:在XML和JSON轉換

>> 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" 

第一行負載。第二行建立一個JSON樣本用於測試。第三行使用假裝的JSON,對其進行解碼,然後將其轉換爲XML。

1

其他答案不允許簡單的遞歸轉換。正如this answer on Code Review中所解釋的那樣,您需要一個自定義助手來創建您正在查找的簡單格式。

它會變成這樣......

data = [ 
    { 'name' => 'category1', 
    'subCategory' => [ 
     { 'name' => 'subCategory1', 
     'product' => [ 
      { 'name' => 'productName1', 
      'desc' => 'desc1' }, 
      { 'name' => 'productName2', 
      'desc' => 'desc2' } ] 
     } ] 
    }, 
    { 'name' => 'category2', 
    'subCategory' => [ 
     { 'name' => 'subCategory2.1', 
     'product' => [ 
      { 'name' => 'productName2.1.1', 
      'desc' => 'desc1' }, 
      { 'name' => 'productName2.1.2', 
      'desc' => 'desc2' } ] 
     } ] 
    }, 
] 

...這個:

<?xml version="1.0"?> 
<root> 
    <category> 
    <name>category1</name> 
    <subCategory> 
     <name>subCategory1</name> 
     <product> 
     <name>productName1</name> 
     <desc>desc1</desc> 
     </product> 
     <product> 
     <name>productName2</name> 
     <desc>desc2</desc> 
     </product> 
    </subCategory> 
    </category> 
    <category> 
    <name>category2</name> 
    <subCategory> 
     <name>subCategory2.1</name> 
     <product> 
     <name>productName2.1.1</name> 
     <desc>desc1</desc> 
     </product> 
     <product> 
     <name>productName2.1.2</name> 
     <desc>desc2</desc> 
     </product> 
    </subCategory> 
    </category> 
</root>