This code will take an input CSV file and output XML. IT was easy to write, but I haven't found anything out there to do this. The first line of the CSV file should contain the element names.
1
2
3
4 require 'csv'
5
6 print "CSV file to read: "
7 input_file = gets.chomp
8
9 print "File to write XML to: "
10 output_file = gets.chomp
11
12 print "What to call each record: "
13 record_name = gets.chomp
14
15 csv = CSV::parse(File.open(input_file) {|f| f.read} )
16 fields = csv.shift
17
18 puts "Writing XML..."
19
20 File.open(output_file, 'w') do |f|
21 f.puts '<?xml version="1.0"?>'
22 f.puts '<records>'
23 csv.each do |record|
24 f.puts " <#{record_name}>"
25 for i in 0..(fields.length - 1)
26 f.puts " <#{fields[i]}>#{record[i]}</#{fields[i]}>"
27 end
28 f.puts " </#{record_name}>"
29 end
30 f.puts '</records>'
31 end
32
33 puts "Contents of #{input_file} written as XML to #{output_file}."