CVS to XML converter

#!/usr/bin/ruby
 
require 'csv'
 
print "CSV file to read: "
input_file = gets.chomp
 
print "File to write XML to: "
output_file = gets.chomp
 
print "What to call each record: "
record_name = gets.chomp
 
csv = CSV::parse(File.open(input_file) {|f| f.read} )
fields = csv.shift
 
puts "Writing XML..."
 
File.open(output_file, 'w') do |f|
  f.puts '<?xml version="1.0"?>'
  f.puts '<records>'
  csv.each do |record|
    f.puts " <#{record_name}>"
    for i in 0..(fields.length - 1)
      f.puts "  <#{fields[i]}>#{record[i]}</#{fields[i]}>"
    end
    f.puts " </#{record_name}>"
  end
  f.puts '</records>'
end # End file block - close file
 
puts "Contents of #{input_file} written as XML to #{output_file}."
 

Download this snippet

Converts a comma seperated file (CVS) to XML.

Twitter Twitter

Tags

Ruby XML CVS

3 Comments to “ CVS to XML converter”

  1. Anonymous  on Sep 25, 2009

    Jj9GGz <a href="http://igwfjareqztf.com/">igwfjareqztf</a>, [url=http://hvfcvsfyqbdd.com/]hvfcvsfyqbdd[/url], [link=http://uukmfjmekznr.com/]uukmfjmekznr[/link], http://wghlooezewrl.com/

  2. Anonymous  on Feb 21, 2010

    ja8rCh <a href="http://gkuepwnabwll.com/">gkuepwnabwll</a>, [url=http://jxultmohtrwu.com/]jxultmohtrwu[/url], [link=http://whxvbezmhhhc.com/]whxvbezmhhhc[/link], http://ldsbnkjjaodh.com/

  3. Anonymous  on Mar 15, 2010

    Sd0eRY <a href="http://hoylheizgezm.com/">hoylheizgezm</a>, [url=http://hxeajvhhbpah.com/]hxeajvhhbpah[/url], [link=http://opgzgsmibbdm.com/]opgzgsmibbdm[/link], http://zxakbzukzzrp.com/

Leave a Comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>