Converting an XML file to a CSV file

Sometime I have the task, of converting a file from one format to the next. Here is my template for converting from XML to CSV using ruby.

require 'rexml/document'

xml_file = File.open("input.xml", "r")
csv_file = File.new("output.txt", "w")

# Header
csv_file.puts "field1, field2, field3\n"

xml = REXML::Document.new(xml_file)

xml.elements.each("array") do |e|
e.elements.each("node") do |f|

field1 = f.elements['field1'].text ? f.elements['field1'].text : ""
field2 = f.elements['field2'].text ? f.elements['field2'].text : ""
field3 = f.elements['field3'].text ? f.elements['field3'].text : ""

csv_file.puts "#{field1}, #{field2}, #{field3}\n"

end
end

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • bodytext
  • del.icio.us
  • Google
  • StumbleUpon
  • Technorati
  • description
  • Facebook
  • Reddit
  • Slashdot
  • TwitThis

This post was written by .

More Posts by   Visit 's Website

Leave a Reply