Ruby, Scala and XML

J Aaron Farr on Sun, 22 Apr 2007

I've been programming fair bit in Ruby lately, but I've had my eye on Scala as well. It's XML support (not to mention integration with Java) makes it a tempting platform. Here's an example of Ruby with REXML:


  require 'rexml/document'
  include REXML
  xml = Document.new(File.open("hydrogen.atom"))
  id = xml.elements["//id"][0]
  puts id

Now for the Scala


  import scala.xml.XML
  object AtomTest {
    val doc = XML.loadFile("hydrogen.atom")
    val id = (doc \ "id")(0)
    def main(args: Array[String]) = 
         Console.println(id)
  }

Pretty similiar, eh? Well here are two great things about Scala: first, we can inline the XML as so:


  import scala.xml.XML
  object AtomTest {
  val doc = 
    <entry xmlns="http://www.w3.org/2005/Atom" 
           xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" 
           xmlns:dc="http://purl.org/dc/elements/1.1/">
      <title>A simple Atom test</title>
      <id>http://localhost/sandbox/hydrogen</id>
      <updated>2007-04-05T12:30:00Z</updated>
      <author>
	<name>root</name>
	<uri>http://localhost:3000/users/root</uri>
	<email>farra@localhost</email>
      </author>
      <content type="application/rdf+xml">
        <rdf:Description rdf:ID="http://localhost/sandbox/hydrogen">
          <dc:comment>This is just a comment</dc:comment>
          <dc:description>The simplest atom is hydrogen</dc:description>
        </rdf:Description>         
      </content>
    </entry>;
   val id = (doc \ "id")(0)
   def main(args: Array[String]) =  Console.println(id)
  }

Now let's look at one other difference between the two. Notice we're outputting the entire element, not just its text. The Ruby output is this:


  <id>http://localhost/sandbox/hydrogen</id>

But with scala, our output is this (prettied up a bit):


  <id xmlns:dc="http://purl.org/dc/elements/1.1/" 
      xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" 
      xmlns="http://www.w3.org/2005/Atom">
        http://localhost/sandbox/hydrogen
  </id>

Scala maintains the XML namespaces! Sweet!

Quirky Ruby

William Taysom on Sat, 20 Jan 2007

In an effort to adapt Ruby to the idiosyncrasies of people, Ruby has developed a number of idiosyncrasies of its own. For example, I’m not entirely sure if anyone actually knows Ruby’s grammar; and if so, I wonder their motivation for subtlety like this:

~> irb
? p ([1] + [3]).join(",")
"1,3"
? p([1] + [3]).join(",")
[1, 3]
NoMethodError: undefined method `join' for nil:NilClass
        from (irb):31
?

It’s not exactly simple, though remember Matz said, “I’m trying to make Ruby natural, not simple.” Then the question is whether or not its natural. I guess that depends entirely on one’s nature.

Tags ,
plants