Post by Peter Cooper on June 27th, 2006
Cobra vs Mongoose: Easy Hash to XML serialization

- HTTParty: Quick Web Service Consumption From Any Ruby Class
- 21 Ruby Tricks You Should Be Using In Your Own Code
- BOSSMan: Build Your Own Search Engine With Yahoo And Ruby


Cobra vs Mongoose is a Ruby library by Paul Battley that makes it easy to convert between XML and Ruby hashes (in both directions). It's a good alternative to YAML or JSON. It's available as a gem with gem install -r cobravsmongoose. Here's some demonstration code:
require 'rubygems' require_gem 'cobravsmongoose' require 'cobravsmongoose' xml = %q{ <people> <person>Fred</person> <person>Chris</person> <person age="10">Bert</person> </people> } puts CobraVsMongoose.xml_to_hash(xml).inspect # => {"people"=>{"person"=>[{"$"=>"Fred"}, {"$"=>"Chris"}, {"@age"=>"10", "$"=>"Bert"}]}}
You can combine this with the JSON library to convert from XML to hash to JSON, meaning you can convert between all three formats.

Click here to add on del.icio.us









June 28th, 2006 at 7:22 am
This is in the Rails trunk at the moment!
June 29th, 2006 at 9:06 am
Thanks for the mention. It prompted me to release a slightly updated version that had been sitting on my hard disk. The improvements are:
* Inbuilt xml_to_json/json_to_xml methods
* It can accept REXML as the XML source, as well as anything that responds to to_s with valid XML.
You don't need that require_gem line, by the way.
In response to Joey's comment: Although there is now XML-hash conversion in Rails, it's not mine! It uses a different conversion schema which is a bit simpler to use, but seems to give a slightly lower-fidelity rendition. Rails's converter also does typecasting, which could be helpful or not, depending on the circumstances.
June 29th, 2006 at 11:07 am
Excellent news, Paul. Thanks for the updates!
Regarding the require_gem line.. I found I needed it otherwise it complained. This may be a quirk of my setup though, but is probably something I should investigate. I find I usually need to add the require_gem lines whenever working with gems otherwise I get complaints.