Ruby, Part 3 — XML
Eventually, I have write a script that does something with XML. I used to muck a lot with RSS stuff, but lately it’s been using GPX files. Regardless of the type of XML, I’m always mucking around with it and I’m comfortable with XPATH, DOM, and other accesses. I decided this would be my next test with Ruby — XML parsing.
I chose REXML simply because my little bit of searching seemed to show that it is the best — with “best” maybe being easiest to use, faster, etc. I thought I would dedicate part of my morning writing a script that would spit out the name of all my found geocaches that I have in a GPX file. This actually took about 15 minutes, thanks to the really good REXML Tutorial:
#!/usr/bin/ruby
require "rexml/document"
file = File.new("/home/mikeh/stuff/caches/found.gpx")
doc = REXML::Document.new file
doc.elements.each("//wpt/name") { |tag| puts tag.text }
file.close
This is a lot nicer than Python’s minidom , which is what I usually use. I have also started using ElementTree, which I like better, except for having to put the namespace at the beginning of each tag, even though it’s declared as the default namespace. That makes mucking with valid GPX files a nuisanceat best, and ugly at worst. But in Ruby, this was a piece of cake. In fact, it took me longer to write this post than to write the script.