Ruby Weekly is a weekly newsletter covering the latest Ruby and Rails news.

Cobra vs Mongoose: Easy Hash to XML serialization

By Peter Cooper / June 27, 2006

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.

Comments

  1. Joey says:

    This is in the Rails trunk at the moment!

  2. Paul Battley says:

    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.

  3. Peter Cooper says:

    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.

Other Posts to Enjoy

Twitter Mentions