DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Ruby: Convert CSV To XML

10.05.2010
| 2900 views |
  • submit to reddit
        // Convert CSV to XML, control each field for UTF8 characters and everything in window

#!/usr/local/bin/ruby w
require 'fox16'
require 'csv'

include Fox

def clean_up dirty_text
  newstr = ""
  dirty_text.length.times do |i|
    character = dirty_text[i]
    newstr += if character < 0x80
      character.chr
    elsif character < 0xC0
      "\xC2" + character.chr
    else
      "\xC3" + (character - 64).chr
    end
  end
  newstr
end

class HorizontalFrame < FXMainWindow
  
  def initialize(app)
    super(app, "Convert from CVS v XML", :width => 525, :height => 235, :padding => 10)
    hframe = FXHorizontalFrame.new(self)
    @choice = FXDataTarget.new(0)
    
    p = FXMatrix.new(self, :opts => MATRIX_BY_COLUMNS)
    FXLabel.new(p, "CSV file: ")    
    @CSV_target = FXDataTarget.new("")
    name_text = FXTextField.new(p, 80,
      :target => @CSV_target, :selector => FXDataTarget::ID_VALUE)
    @CSV_target.connect(SEL_COMMAND) do
      @CSV_dat = @CSV_target.value
    end    
    FXLabel.new(p, "XML file: ")    
    @XML_target = FXDataTarget.new("")
    xml_text = FXTextField.new(p, 80,
      :target => @XML_target, :selector => FXDataTarget::ID_VALUE)
    @XML_target.connect(SEL_COMMAND) do
      @XML_dat = @XML_target.value
    end    
    
    child1 = FXButton.new(hframe, "Convert from CSV v XML")
    child1.connect(SEL_COMMAND)     {     input_file = @CSV_dat
								       output_file = @XML_dat
       									record_name = "line"
       									csv = CSV::parse(File.open(input_file) {|f| f.read} )
       									fields = csv.shift
       									File.open(output_file, 'w') do |f|
       									  f.puts '<?xml version="1.0"?>'
       									  f.puts '<records>'
       									  csv.each do |record|
       									    f.puts " <#{record_name}>"
       									    for i in 0..(fields.length - 1)
       									      record[i] = clean_up record[i]
       									      f.puts "  <#{fields[i]}>#{record[i]}</#{fields[i]}>"
       									    end
       									    f.puts " </#{record_name}>"
       									  end
  									 f.puts '</records>'
      									end  
      									exit  }    
    end

  def create
    super
    show(PLACEMENT_SCREEN)
  end
  
end

if __FILE__ == $0
  FXApp.new do |app|
    HorizontalFrame.new(app)
    app.create
    app.run
  end
end