How to Write Xml in Ruby

In Ruby there is no built-in support for parsing and writing xml. There are however a couple of gems (packages) that allow you to do exactly this. If you are working in Rails - you have this for “free” with ActiveSupport (which you could also just require as a standalone package). This gives you a to_xml on a hash which is dead easy to use. There is also the xmlsimple gem which is a port of the same library from perl.

My favourite tool for working with xml in ruby is nokogiri though.

require 'nokogiri'

user = {:name => "Claus Witt", :powers => ["awesomeness", "code"]}
builder = { |xml|

    xml.user { user[:name]
        xml.powers { |xml|
            user[:powers].each { |power|

puts builder.to_xml

This will output an xml looking like this:

<?xml version="1.0"?>
  <name>Claus Witt</name>