Return to Snippet

Revision: 19408
at October 22, 2009 18:10 by chrisaiv


Initial Code
require 'rexml/document'

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

xml = REXML::Document.new( xml_file  )

counter = 0
xml.elements.each("images") do |e|
  e.elements.each("image") do |f|
    counter = counter + 1

    csv_file.puts f.elements['src'].text  + "|" + f.elements['caption'].text  + "|" + f.elements['uri'].text + "|"
  end
end

Initial URL
http://developer.yahoo.com/ruby/ruby-xml.html

Initial Description
I had an XML file that I needed to convert to CSV.  In order to make things easier for myself, I used a pipe | symbol instead of a comma so that there would be no parsing errors later.  I also ended up writing the file to a Txt file and importing it as such to Microsoft Excel.

Initial Title
Ruby: Parse XML to CSV

Initial Tags
ruby, xml

Initial Language
Ruby