A simple example - XML from a Ruby program
Archive - Originally posted on "The Horse's Mouth" - 2010-04-10 07:16:50 - Graham EllisThe REXML module is supplied with the Ruby distribution and provides a neat way of handling XML data in Ruby. There is a very wide range of methods available, though, and sometimes it's hard to see the wood for the trees.
So here - to start - is the [full source] of an application which reads an RSS feed and splits out the title elements. I've actually done the job twice - once by finding the elements directly, and then (slighty more sophisticated) by accessing elements within elements.
require 'rexml/document'
include REXML
file = File.new("myrssfeed.xml")
doc = Document.new(file)
# ------------- Reading from the document structure
# ------------- This is an RSS feed - few attributes ;-)
doc.elements.each("rss/channel/item/title") do |element|
puts element
end
puts " AGAIN -----------------"
doc.elements.each("rss/channel/item") do |element|
element.elements.each("title") do |ttl|
puts ttl
end
end
Sample output using [this data]:
Dorothy-2:ra10 grahamellis$ ruby x1.rb
<title>History is all around us</title>
<title>A more informed decision than ever before</title>
<title>For loop - checked once, or evety time? Ruby v Perl comparison and contrast</title>
<title>__index and __newindex in Lua - metatable methods</title>
<title>Old trackways and routes near Melksham</title>
<title>The bull on the footpath</title>
<title>A walk on the Kennet and Avon</title>
<title>Error trapping in Lua - no exceptions.</title>
<title>Hotel booking in Melksham made easy!</title>
<title>A walk within without - Melksham Without</title>
<title>Lua Metatables</title>
<title>First and last match with Regular Expressions</title>
<title>Is Lua an Object Oriented language?</title>
<title>The same very simple program in many different programming languages</title>
<title>Lua tables - they are everything</title>
AGAIN -----------------
<title>History is all around us</title>
<title>A more informed decision than ever before</title>
<title>For loop - checked once, or evety time? Ruby v Perl comparison and contrast</title>
<title>__index and __newindex in Lua - metatable methods</title>
<title>Old trackways and routes near Melksham</title>
<title>The bull on the footpath</title>
<title>A walk on the Kennet and Avon</title>
<title>Error trapping in Lua - no exceptions.</title>
<title>Hotel booking in Melksham made easy!</title>
<title>A walk within without - Melksham Without</title>
<title>Lua Metatables</title>
<title>First and last match with Regular Expressions</title>
<title>Is Lua an Object Oriented language?</title>
<title>The same very simple program in many different programming languages</title>
<title>Lua tables - they are everything</title>
Dorothy-2:ra10 grahamellis$