Posted By

chrisaiv on 07/18/11


Tagged

ruby xml csv


Versions (?)

Ruby: CSV to XML (Version 2)


 / 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.

  1. #!/usr/bin/ruby
  2.  
  3. =begin
  4. filename = 'data.csv'
  5. file = File.new(filename, 'r')
  6.  
  7. file.each_line("\n") do |row|
  8.   columns = row.split(",")
  9.  
  10.   break if file.lineno > 10
  11. end
  12. =end
  13.  
  14. require 'rubygems'
  15. #sudo gem update excelsior
  16. require 'excelsior'
  17.  
  18. def read_csv( file )
  19. rows = Array.new
  20. Excelsior::Reader.rows( File.open( file , 'r') ) do |row|
  21. rows << row
  22. end
  23. return rows
  24. end
  25.  
  26. def generate_xml( array )
  27. output = File.new("CSV_to_XML.xml", "w")
  28. output.puts '<?xml version="1.0" encoding="UTF-8"?>'
  29. output.puts '<records>'
  30.  
  31. array.each do |record|
  32. 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 + '" />'
  33. end
  34.  
  35. output.puts '</records>'
  36. end
  37.  
  38. rows = read_csv( "scholars_list_FINAL.csv" )
  39. generate_xml( rows )

Report this snippet  

You need to login to post a comment.