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 = Nokogiri::XML::Builder.new { |xml|

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

puts builder.to_xml

This will output an xml looking like this:

<?xml version="1.0"?>
<user>
  <name>Claus Witt</name>
  <powers>
    <name>awesomeness</name>
    <name>code</name>
  </powers>
</user>

Related Posts