How do I convert a Ruby hash to XML?

前端 未结 5 770
傲寒
傲寒 2020-12-05 23:04

Here is the specific XML I ultimately need:



  joe@example.com
           


        
相关标签:
5条回答
  • 2020-12-05 23:12

    Gem gyoku very nice.

    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.

    0 讨论(0)
  • 2020-12-05 23:12

    If this data is a model, look at overriding to_xml.

    Otherwise, Builder is a good option.

    0 讨论(0)
  • 2020-12-05 23:14

    I did a short presentation about exactly that topic at my university a while back. Here are the slides (Interesting part starts at >= page 37)

    0 讨论(0)
  • 2020-12-05 23:17

    I would suggest a gem like XmlSimple which provides this kind of facility.

    0 讨论(0)
  • 2020-12-05 23:27

    ActiveSupport adds a to_xml method to Hash, so you can get pretty close to what you are looking for with this:

    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.

    0 讨论(0)
提交回复
热议问题