How to make XML from a Hash

require 'rexle'

def make_xml(h)

  h.map do |name, x|

    value = x.is_a?(Hash) ? make_xml(x) : x
    [name, {}, *value]
  end
end

Example 1:

h = {fun: '123', great: 'tr34'}
a = ['root', {}, '', *make_xml(h)]
doc = Rexle.new a
puts doc.xml pretty: true

Output 1:

<?xml version='1.0' encoding='UTF-8'?>
<root>
  <fun>123</fun>
  <great>tr34</great>
</root>

Example 2:

h = {
  tree: 'Mahogany',
  qty: '146',
  info: {
    url: 'about:blank',
    locations: 'a, b, c'
  }
}

a = ['root', {}, '', *make_xml(h)]
doc = Rexle.new a
puts doc.xml pretty: true

Output 2:

<?xml version='1.0' encoding='UTF-8'?>
<root>
  <tree>Mahogany</tree>
  <qty>146</qty>
  <info>
    <url>about:blank</url>
    <locations>a, b, c</locations>
  </info>
</root>

Resources