Skip to content

Instantly share code, notes, and snippets.

@joseche
Last active October 1, 2015 19:54
Show Gist options
  • Select an option

  • Save joseche/d3fb2c0cdbc6c188eebe to your computer and use it in GitHub Desktop.

Select an option

Save joseche/d3fb2c0cdbc6c188eebe to your computer and use it in GitHub Desktop.
Convert a XML file to a CSV file
# first argument the xml file to convert
# second argument the csv output file
# TODO: it doesn't create the header of the csv file, only values
require 'nokogiri'
require 'pp'
exit unless ARGV.length > 1
exit unless File.exist?(ARGV[0])
xmldoc = Nokogiri::XML(IO.read(ARGV[0]))
File.open(ARGV[1], 'w') do |f|
xmldoc.xpath('/*/*').each do |row_xml|
row_values = row_xml.values
csv_string = row_values.map { |i| '"' + i.to_s.gsub(/['"]/,'\'').gsub(/[\n\r]+/,"\\n") + '"' }
f.puts csv_string.join(',')
end
f.close
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment