I would like to import an XML file from URL using Nokogiri and save it to my postgresql database.
In my schema.rb I have the following table:
create_table "centres", force: :cascade do |t| t.string "name" t.string "c_type" t.text "description" t.float "lat" t.float "long" t.datetime "created_at", null: false t.datetime "updated_at", null: false end
Below is a sample from the file I am importing:
<facility> <id>CG432</id> <facility_name>Cairncry Community Centre</facility_name> <expiration>2099-12-31T23:59:59Z</expiration> <type>Community Centre</type> <brief_description/> <lat>57.1601027</lat> <long>-2.1441739</long> </facility>
I created the following import.rake task in lib/tasks:
require 'rake' require 'open-uri' require 'Nokogiri' namespace :db do task :xml_parser => :environment do doc = Nokogiri::XML(open("http://sample.xml")) doc.css('centre').each do |node| facility_name = node.xpath("centre").text, type = node.xpath("centre").text, brief_description = node.xpath("centre").text, lat = node.xpath("centre").text, long = node.xpath("centre").text, Centre.create(:facility_name => name, :type => c_type, :brief_description => description, :lat => lat, :long => long) end end end
I tried rake db:migrate and also rake -T | grep import. I am fairly new to XML so if you know the answer I would also love for you to explain what is happening there. Thank you!
No comments:
Post a Comment