Cobra vs Mongoose


Cobra vs Mongoose translates XML to and from Ruby Hash objects, following the BadgerFish convention.

The current release is version 0.0.2.


Converting XML to a Ruby Hash

require 'cobravsmongoose'
xml = '<alice><bob>charlie</bob><bob>david</bob></alice>'
# => { "alice" => { "bob" => [{ "$" => "charlie" }, { "$" => "david" }] } }

Converting a Ruby Hash to XML

require 'cobravsmongoose'
hash = { "alice" => { "$" => "bob", "@charlie" => "david" } }
# => <alice charlie='david'>bob</alice>

Note that, due to the fact that Ruby’s hashes do not preserve ordering, the order of XML elements is undefined. For a predictable order, see the sort_keys class attribute.

Converting JSON

If you install the JSON library for Ruby, you can convert XML to and from JSON:

require 'cobravsmongoose'

xml = '<alice><bob>charlie</bob><bob>david</bob></alice>'
# => {"alice":{"bob":[{"$":"charlie"},{"$":"david"}]}}

json = '{"alice":{"$":"bob","@charlie":"david"}}'
# => <alice charlie='david'>bob</alice>


For more details, you can browse the rdoc-generated documentation online.

Getting it

Cobra vs Mongoose is available as a tarball or gem on its RubyForge page.

You should also be able to install it directly using RubyGems:

gem install -r cobravsmongoose

Since JSON is not required for the basic functionality, the json gem will not automatically be installed by RubyGems. To use JSONXML conversion, you must install it separately:

gem install -r json


This code is free to use under the terms of the MIT licence. If you’d like to negotiate a different licence for a specific use, just contact me—I’ll almost certainly permit it.


Comments are welcome. Send an email to

Paul Battley, 29th June 2006