Some times ago I had to parse a XML messages’ file to produce some i18n properties files.

I decided to try it with Ruby, mainly because of two reasons:

  1. I’m continuosly exploring some dynamically-typed languages, like Python and Ruby
  2. I wanted to try the conciseness of programming with closures

So, I used the REXML API to process the XML file. The result code looks like the one below:

   1:require 'rexml/document'
   2:include REXML
   3:englishFile = File.new('englishFileName', 'w+')
   4:spanishFile = File.new('spanishFileName', 'w+')
   5:portugueseFile = File.new('portugueseFileName', 'w+')
   6:errorMessagesFile = File.new("errorMessages.xml")
   7:document = Document.new(file)
   8:root = document.root
   9:root.each_element("Property") do |propertyTag|
  10:  id = propertyTag.attributes['id']   
  11:  propertyTag.each_element("element") do |elementTag|
  12:      elementAttr = elementTag.attributes['otherTag']
  13:      error = elementTag.text == nil ? "" : "#{id} = #{elementTag.text}\n"
  14:      if elementAttr = "pt"
  15:          portugueseFile << error
  16:      elsif elementAttr == "es"
  17:          spanishFile << error
  18:      else 
  19:          portugueseFile << error
  20:      end
  21:  end
  22:end
  23:errorMessagesFile.close()
  24:englishFile.close()
  25:spanishFile.close()
  26:portugueseFile.close()
  27:  

I like to solve this kind of tasks with programming languages (mainly the dynamically-typed ones..) I don’t know very much because it’s an opportunity to put my hands on them! This way I could experience Ruby’s closures syntax, it was really nice and I’m gonna try something new with it often!

*Updated: line 13