Created
April 26, 2017 22:53
-
-
Save bxt/454bb3b6ad7d2fdba0a5b1efb9b45d86 to your computer and use it in GitHub Desktop.
Convert XML to CSV file using Ruby (nokogiri)
This file contains 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
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