How to Convert a Ruby Hash to Xml

How do I convert a Ruby hash to XML?

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.

How to convert an array of hashes into XML in Rails?

try this:

    pp entries.to_xml(:root => 'map', :children => 'entry', :indent => 0, :skip_types => true)

source: http://apidock.com/rails/Array/to_xml

How do I convert ruby hash to proper xml format

See Nokogiri::XML::Builder.

Note that your example is not a valid XML document because it is missing a root element. Assuming you want a document rooted with an element named object:

require 'nokogiri'

h = {
name: 'Test name' ,
values: [123, 456, 789],
}

builder = Nokogiri::XML::Builder.new do |xml|
xml.object {
xml.name h[:name]
xml.values {
h[:values].each { |v| xml.elements v }
}
}
end

puts builder.to_xml
# <?xml version="1.0"?>
# <object>
# <name>Test name</name>
# <values>
# <elements>123</elements>
# <elements>456</elements>
# <elements>789</elements>
# </values>
# </object>

Ruby hash to XML: How would I create duplicate keys in a hash for repeated XML xpaths?

Okay I believe I figured it out. You have to use Hash#compare_by_identity. I believe this makes it so that the key lookups are done using object id as opposed to string matches.

I found it in "Ruby Hash with duplicate keys?".

{}.compare_by_identity

    h1 = {}
h1.compare_by_identity
h1["a"] = 1
h1["a"] = 2
p h1 # => {"a"=>1, "a"=>2}

converting hash to XML using xmlsimple in ruby

The key for the outer hash is definitely 1234 and 234. xmlsimple is doing the correct parsing. You havent mentioned of MyKeys or MyKey in your hash. You should convert the hash to your required format before converting it to xml.

hash = {
'1234' => {"key1"=>1234,"key2"=>"sdfsdf","key3"=>"sdfsdfs"},
'234' => {"key1"=>234,"key2"=>"sdfsdf","key3"=>"sdfsdfs"}
}
converted_hash = Hash[hash.map{|k, v| ["MyKey", v]}]
result_hash = {"MyKeys" => converted_hash}

Use xmlsimple on this hash.

How to convert a nested hash into XML using Nokogiri

How about this?

class Hash
  def to_xml
    map do |k, v|
      text = Hash === v ? v.to_xml : v
      "<%s>%s</%s>" % [k, text, k]
    end.join
  end
end

h.to_xml
#=> "<foo>bar</foo><foo1><foo2>bar2</foo2><foo3>bar3</foo3><foo4><foo5>bar5</foo5></foo4></foo1>"

How to remove hash /hash from format.xml

render :xml => @objects.to_xml(:root => :root_name, :skip_types => true)


Related Topics



Leave a reply



Submit