Skip to content

Instantly share code, notes, and snippets.

@billspat
Created May 15, 2014 15:35
Show Gist options
  • Save billspat/178f94d563dc1d819931 to your computer and use it in GitHub Desktop.
Save billspat/178f94d563dc1d819931 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
# very simple csv to xml convert, targeted for ruby 2.0 +
# depends on activesupport 4 gem which add #to_xml method to hash and array
require 'csv'
require "active_support/core_ext"
if ARGV.length < 1 || ARGV[0] == "-h"
puts "usage : ruby csv2xml.rb myfile.csv > myfile.xml"
exit
end
infile = ARGV[0]
csv = CSV.new(File.new(infile), :headers => true, :header_converters => :symbol, :converters => [:all])
row_hash = csv.to_a.map{|row| row.to_hash }
file_name_for_root_element= File.basename(infile, File.extname(infile))
puts row_hash.to_xml(:root => file_name_for_root_element)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment