Cover by Michael Fitzgerald

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

Processing XML

Ruby has a growing number of XML facilities. Sean Russell's Ruby Electric XML (REXML) is built into Ruby, so it's an obvious choice for discussion (http://www.germane-software.com/software/rexml). Builder is built into Rails, so we will pay some attention to that as well (http://rubyforge.org/projects/builder).

Here are a couple more that I won't be showing you. Libxml-Ruby, a C-language Ruby binding to GNOME's libxml2 library, is a speedy alternative (see http://libxml.rubyforge.org). There is also XmlSimple, a Ruby translation of the Perl module XML::Simple (http://xml-simple.rubyforge.org). XmlSimple requires REXML.

The following discussions assume that you already know XML, so I won't be explaining what elements or attributes are, and so forth. There is so much I could tell you about, but I must be brief. You'll learn just enough about processing XML to be a little heady with the lunchroom crowd.

REXML

Because REXML is already part of Ruby, you get it free of charge. Example 10-1 shows a small program that creates an XML document from a here document and then writes the document out to standard output.

Example 10-1. mondo.rb

#!/usr/bin/env ruby

require 'rexml/document'
include REXML

address = <<XML
<address>
 <name><given>Mondo</given><family>Mangrove</family></name>
 <street>9876 Trekker St.</street>
 <city>Granola</city>
 <state>Colorado</state>
 <code>81000</code>
 <country>USA</country>
</address>
XML

document = Document.new( address )
puts document

You must require

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required