Last active
October 1, 2015 19:54
-
-
Save joseche/d3fb2c0cdbc6c188eebe to your computer and use it in GitHub Desktop.
Convert a XML file to a CSV file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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