Thursday, February 25, 2010

Using REXML to read small xml files and load into database table

Save the following code in lib folder of your application as read_xml_file.rb . using command prompt run " ruby script/runner lib/read_xml_file.rb". The following code is possible to read only small xml files ( usually in kbs).


require 'rexml/document'
require 'rubygems'
include REXML
#def import_xml(tag)
file= File.new(RAILS_ROOT + "/file.xml")
doc= Document.new(file.read)

Ingredient.benchmark("Truncating ingredient table and inserting new records") do
#truncate ingredient table
ActiveRecord::Base.connection.execute("TRUNCATE ingredient")
# read table contents
XPath.each( doc, "//INGREDIENT_SUBSTANCES//ING" ){|ingredient|
ingredient_params = {}
#if there are more than one attributes for table then create a hash.
ingredient.children.each do |child|
key = "#{child.name}".to_sym
if key.to_s == "ISID"
@isid_value = child.text
else
ingredient_params[key] = child.text
end
#@desc_value = child.text if key.to_s == "DESC"

end
#create new instance
ingredient = Ingredient.new(ingredient_params)
#set the primary key if mass assigning of primary key is not possible.
ingredient.ISID = @isid_value
#save
ingredient.save
}
end

No comments:

Post a Comment