This very simple code will take a file saved by
mysql --xml
and convert it to CSV format, with a header. I know there’s a MySQL option to save a file as a CSV or TSV, but I needed this for my situation.
The code uses Hpricot (by Why the Lucky Stiff) for XML parsing.
require 'hpricot'
xml = Hpricot(open(ARGV[0]))
# Header line - first set of attribute values
puts ((xml/'resultset/row').first/'field').map { |e| e.attributes['name'] }.join(', ')
lines = (xml/'resultset/row').map do |r|
(r/'field').map { |f| f.inner_text }.join(', ').strip
end
puts lines.join("\n")
I wonder – is there a better, shorter way to do this?