Importing An Xml Document Into A Rails Database?
I've been reading through tutorial after tutorial, but nothing seems to be working out for me. The goal is to take a XML document with elements and attributes and insert the data i
Solution 1:
I did something similar using the Nokogiri library.
doc = Nokogiri::XML(xml_data)
doc.css('book').each do|node|
children = node.children
Book.create(
:isbn => node['ISBN'],
:title => children.css('title').inner_text,
:description => children.css('description').inner_text,
:author => children.css('author').inner_text
)
endUpdate
You could create a quick test by doing this:
First install the nokogiri gem:
gem install nokogiri
Then create a file called text_xml.rb with the contents:
require 'nokogiri'
doc = Nokogiri::XML('<?xml version="1.0"?><library><NAME><![CDATA[Favorite Books]]></NAME><bookISBN="11342343"><title>To Kill A Mockingbird</title><description><![CDATA[Description#1]]></description><author>Harper Lee</author></book><bookISBN="989894781234"><title>Catcher in the Rye</title><description><![CDATA[This is an extremely intense description.]]></description><author>J. D. Salinger</author></book><bookISBN="123456789"><title>Murphy\'s Gambit</title><description><![CDATA[Daughter finds her dad!]]></description><author>Syne Mitchell</author></book></library>')
doc.css('book').each do |node|
children = node.children
book = {
"isbn" => node['ISBN'],
"title" => children.css('title').inner_text,
"description" => children.css('description').inner_text,
"author" => children.css('author').inner_text
}
puts book
end
And finally run:
ruby test_xml.rb
I suspect you weren't escaping the single quote in Murphy's Gambit when you pasted in your xml.
Post a Comment for "Importing An Xml Document Into A Rails Database?"