代码之家  ›  专栏  ›  技术社区  ›  Shpigford

如何将Ruby哈希转换为XML?

  •  30
  • Shpigford  · 技术社区  · 15 年前

    <?xml version="1.0" encoding="UTF-8"?>
    <customer>
      <email>joe@example.com</email>
      <first_name>Joe</first_name>
      <last_name>Blow</last_name>
    </customer>
    

    但是假设我有一个控制器( Ruby on Rails )也就是将数据发送到一个方法。我更愿意将其作为散列发送,如下所示:

    :first_name => 'Joe',
    :last_name => 'Blow',
    :email => 'joe@example.com'
    

    5 回复  |  直到 8 年前
        1
  •  73
  •   the_storyteller Latinbooker    6 年前

    ActiveSupport添加了一个 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')
    

    <?xml version="1.0" encoding="UTF-8"?>
    <customer>  
       <last-name>Blow</last-name>  
       <first-name>Joe</first-name>  
       <email>joe@example.com</email>
    </customer>
    

    请注意,下划线将转换为破折号。

        2
  •  5
  •   vk26    7 年前

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

        3
  •  3
  •   Steve Madsen    15 年前

    如果此数据是模型,请查看覆盖 to_xml .

    否则,, Builder

        4
  •  3
  •   plainprogrammer    15 年前

    我建议买一个宝石一样的 XmlSimple 它提供了这种设施。

        5
  •  2
  •   Marc Seeger    15 年前

    不久前,我在大学里做了一个关于这个主题的简短演讲。 Here 幻灯片(有趣的部分从>=第37页)