Skip to content

Instantly share code, notes, and snippets.

@bxt
Created April 26, 2017 22:53
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bxt/454bb3b6ad7d2fdba0a5b1efb9b45d86 to your computer and use it in GitHub Desktop.
Save bxt/454bb3b6ad7d2fdba0a5b1efb9b45d86 to your computer and use it in GitHub Desktop.
Convert XML to CSV file using Ruby (nokogiri)
require 'csv'
require 'nokogiri'
filename = "timeentries"
doc = File.open("#{filename}.xml") { |f| Nokogiri::XML(f) }
entries = doc.css('time-entry')
CSV.open("#{filename}.csv", "wb") do |csv|
header = entries.first.element_children.map(&:name)
csv << header
entries.each do |entry|
if header != entry.element_children.map(&:name)
raise "malformed!"
end
csv << entry.element_children.map(&:content)
end
end
puts "Converted #{entries.size} elements."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment