<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DZone Snippets: Jnorris's Code Snippets</title>
    <link>http://snippets.dzone.com/posts</link>
    <pubDate>Thu, 21 Aug 2008 01:21:35 GMT</pubDate>
    <description>DZone Snippets: Jnorris's Code Snippets</description>
    <item>
      <title>Ruby CSV to XML Converter</title>
      <link>http://snippets.dzone.com/posts/show/3701</link>
      <description>This code will take an input CSV file and output XML. IT was easy to write, but I haven't found anything out there to do this. The first line of the CSV file should contain the element names.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;#!/usr/bin/ruby&lt;br /&gt;&lt;br /&gt;require 'csv'&lt;br /&gt;&lt;br /&gt;print "CSV file to read: "&lt;br /&gt;input_file = gets.chomp&lt;br /&gt;&lt;br /&gt;print "File to write XML to: "&lt;br /&gt;output_file = gets.chomp&lt;br /&gt;&lt;br /&gt;print "What to call each record: "&lt;br /&gt;record_name = gets.chomp&lt;br /&gt;&lt;br /&gt;csv = CSV::parse(File.open(input_file) {|f| f.read} )&lt;br /&gt;fields = csv.shift&lt;br /&gt;&lt;br /&gt;puts "Writing XML..."&lt;br /&gt;&lt;br /&gt;File.open(output_file, 'w') do |f|&lt;br /&gt;  f.puts '&lt;?xml version="1.0"?&gt;'&lt;br /&gt;  f.puts '&lt;records&gt;'&lt;br /&gt;  csv.each do |record|&lt;br /&gt;    f.puts " &lt;#{record_name}&gt;"&lt;br /&gt;    for i in 0..(fields.length - 1)&lt;br /&gt;      f.puts "  &lt;#{fields[i]}&gt;#{record[i]}&lt;/#{fields[i]}&gt;"&lt;br /&gt;    end&lt;br /&gt;    f.puts " &lt;/#{record_name}&gt;"&lt;br /&gt;  end&lt;br /&gt;  f.puts '&lt;/records&gt;'&lt;br /&gt;end # End file block - close file&lt;br /&gt;&lt;br /&gt;puts "Contents of #{input_file} written as XML to #{output_file}."&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Mon, 19 Mar 2007 19:17:05 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/3701</guid>
      <author>jnorris (Jason Norris)</author>
    </item>
  </channel>
</rss>
