How to convert a nested hash into XML using Nokogiri

Viewed 5700

I have many levels of a nested hash like:

 { :foo => 'bar', :foo1 => { :foo2 => 'bar2', :foo3 => 'bar3', :foo4 => { :foo5 => 'bar5' }}}

How can I convert them into an XML like this?:

<foo>bar</foo>
<foo1>
    <foo2>bar2</foo2>
    <foo3>bar3</foo3>
    <foo4>
      <foo5>bar5</foo5>
    </foo4>
</foo1>

I tried the xml.send method, but it converts the above nested hash to:

<foo1 foo3="bar3" foo4="foo5bar5" foo2="bar2"/>
<foo>bar</foo>
3 Answers

If you are using Rails you could use the built-in to_xml method.

c = { :foo => 'bar', :foo1 => { :foo2 => 'bar2', :foo3 => 'bar3', :foo4 => { :foo5 => 'bar5' }}}

xml = c.to_xml

=> "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<hash>\n  <foo>bar</foo>\n  <foo1>\n    <foo2>bar2</foo2>\n    <foo3>bar3</foo3>\n    <foo4>\n      <foo5>bar5</foo5>\n    </foo4>\n  </foo1>\n</hash>\n"
Related