/ Published in: Ruby

I use this code snippet all the time. It allows me to parse a CSV file and transform it into an XML file.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
#!/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 )
Comments
