Ruby

Converting an XML file to a CSV file

Sometime I have the task, of converting a file from one format to the next. Here is my template for converting from XML to CSV using ruby.

require 'rexml/document'

xml_file = File.open("input.xml", "r")
csv_file = File.new("output.txt", "w")

# Header
csv_file.puts "field1, field2, field3\n"

xml = REXML::Document.new(xml_file)

xml.elements.each("array") do |e|
e.elements.each("node") do |f|

field1 = f.elements['field1'].text ? f.elements['field1'].text : ""
field2 = f.elements['field2'].text ? f.elements['field2'].text : ""
field3 = f.elements['field3'].text ? f.elements['field3'].text : ""

csv_file.puts "#{field1}, #{field2}, #{field3}\n"

end
end

Ruby Toolbox

The Ruby Toolbox_ Know your options!I just wanted to quickly share a recent find.  Ruby Toolbox is a community driven site, were people can vote on their plugin/gem of choice. It doesn’t always make since to build functionality from scratch. However knowing which gem to uses for your business problem is not always obvious. Also, when you are not happy with the most popular plugin or gem, its good to know that you are not pidgon holed. You have options, and at a glace you can see what those options are.