Cobra vs Mongoose

About

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

The current release is version 0.0.2.

Usage

Converting XML to a Ruby Hash

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

Converting a Ruby Hash to XML

require 'cobravsmongoose'
hash = { "alice" => { "$" => "bob", "@charlie" => "david" } }
CobraVsMongoose.hash_to_xml(hash)
# => <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>'
CobraVsMongoose.xml_to_json(xml)
# => {"alice":{"bob":[{"$":"charlie"},{"$":"david"}]}}

json = '{"alice":{"$":"bob","@charlie":"david"}}'
CobraVsMongoose.json_to_xml(json)
# => <alice charlie='david'>bob</alice>

Documentation

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

Licence

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.

Contact

Comments are welcome. Send an email to pbattley@gmail.com.

Paul Battley, 29th June 2006