How can I convert JSON to XML in Ruby?

前端 未结 4 1550
有刺的猬
有刺的猬 2021-02-20 18:28

Is there any way to convert JSON to XML in Ruby?

4条回答
  •  囚心锁ツ
    2021-02-20 19:13

    The other answers do not allow for simple recursive conversions. As explained in this answer on Code Review, you'll need a custom helper to create the simple format you're looking for.

    It will turn this...

    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' } ]
          } ]
      },
    ]
    

    ...into this:

    
    
      
        category1
        
          subCategory1
          
            productName1
            desc1
          
          
            productName2
            desc2
          
        
      
      
        category2
        
          subCategory2.1
          
            productName2.1.1
            desc1
          
          
            productName2.1.2
            desc2
          
        
      
    
    

提交回复
热议问题