Posted By

chrisaiv on 10/22/09


Tagged

ruby xml


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

kentonnewby
dimispaceman


Ruby: Parse XML to CSV


 / Published in: Ruby
 

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

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.

  1. require 'rexml/document'
  2.  
  3. xml_file = File.open("showcase.xml", "r")
  4. csv_file = File.new("showcase.txt", "w")
  5.  
  6. xml = REXML::Document.new( xml_file )
  7.  
  8. counter = 0
  9. xml.elements.each("images") do |e|
  10. e.elements.each("image") do |f|
  11. counter = counter + 1
  12.  
  13. csv_file.puts f.elements['src'].text + "|" + f.elements['caption'].text + "|" + f.elements['uri'].text + "|"
  14. end
  15. end

Report this snippet  

You need to login to post a comment.