Return to Snippet

Revision: 49192
at July 18, 2011 05:33 by chrisaiv


Initial Code
#!/usr/bin/ruby

=begin
filename = 'data.csv'
file = File.new(filename, 'r')

file.each_line("\n") do |row|
  columns = row.split(",")
  
  break if file.lineno > 10
end
=end

require 'rubygems'
#sudo gem update excelsior
require 'excelsior'

def read_csv( file )
  rows = Array.new
  Excelsior::Reader.rows( File.open( file , 'r') ) do |row|
    rows << row
  end
  return rows
end

def generate_xml( array )
  output = File.new("CSV_to_XML.xml", "w")
  output.puts '<?xml version="1.0" encoding="UTF-8"?>'
  output.puts '<records>'
  
  array.each do |record|
    output.puts "\t" + '<record name="' + record[0].to_s + '" year="' + record[1].to_s + '" section="' + record[2].to_s + '" tile="' + record[3].to_s + '" award="' + record[4].to_s + '" />'
  end
  
  output.puts '</records>'  
end

rows = read_csv( "scholars_list_FINAL.csv" )
generate_xml( rows  )

Initial URL


Initial Description
I use this code snippet all the time.  It allows me to parse a CSV file and transform it into an XML file.

Initial Title
Ruby: CSV to XML (Version 2)

Initial Tags
ruby, xml, csv

Initial Language
Ruby