Reading and writing XML in Ruby

The fastest library for XML parsing and building in Ruby is libxml-ruby. The library does not use the familiar DOM methods, but it's pretty easy to use.

First, install the libxml-ruby gem:

gem install libxml-ruby

To parse an XML string:

require 'xml'

xml = '<?xml version="1.0"?><root><child attr="value">text</child></root>'
root = XML::Parser.string(xml).parse.root
child = root.children.find { |node| == "child" }
attr = child["attr"]

To build an XML document:

require 'xml'

xml =
root ="root")
child ="child", "text")
child["attr"] = "value"
root << child