29 MarConvert a Hash to xml
Monday, 29 March 2010 — 07:01When we get a request in our controller, we use to get request information from “params” parameter in a hash object. Thus, it’s simple for example to get information sent through something simple like:
info_hash = params[:post]In some cases, usually when we want to send to the server a big amount of information, we usually use an xml. Rails converts this xml into a hash form so that we can deal more easily with it. Let’s imagine we get this hash in our controller:
>> test = {"uno"=>["dos"=>"dos_uno","cuatro"=>"cuatro_uno"], "zero"=>"zero_one"}=> {"uno"=>[{"cuatro"=>"cuatro_uno", "dos"=>"dos_uno"}], "zero"=>"zero_one"}And now what if you want to convert that hash to xml?. Rails gives a very simple built in solution for this through vendor/rails/activesupport/lib/active_support/core_ext/array/conversions.rb:
test.to_xml(:skip_types => true,:dasherize => false, :indent => 0, :root => "training")=> "<?xml version=\"1.0\" encoding=\"UTF-8\"?><training><uno><uno><cuatro>cuatro_uno</cuatro><dos>dos_uno</dos></uno></uno><zero>zero_one</zero></training>"
As you can see, it has created nested elements, but there is one thing i don’t like in this case, and that’s the extra element “uno”. How can we get rid of it?
Another way for doing this, is using another built in library from Rails, like XmlSimple. It has two methods, xml_in, and xml_out. We will use xml_out in this case, with AttrPrefix set to true. You can check some more options here:
XmlSimple.xml_out(test, "AttrPrefix"=>true)=> "<opt>\n <uno>\n <cuatro>cuatro_uno</cuatro>\n <dos>dos_uno</dos>\n </uno>\n <zero>zero_one</zero>\n</opt>\n"
You can use some other options to customize your output but at least we managed to remove the extra level. Nice!.
In any case, if you just wanted to get the submitted xml, you’d better use this instead :-)
submitted_xml = request.body