Skip to content

Instantly share code, notes, and snippets.

@weidiaoxiang
Forked from abarringer/gist:846621
Created April 27, 2013 08:29
Show Gist options
  • Save weidiaoxiang/5472338 to your computer and use it in GitHub Desktop.
Save weidiaoxiang/5472338 to your computer and use it in GitHub Desktop.
require 'rubygems'
require 'sqlite3'
require 'rexml/document'
include REXML
xml =<<XML
<records>
<entry><name>abc</name><qty>3</qty></entry>
<entry><name>def</name><qty>5</qty></entry>
<entry><name>ghi</name><qty>2</qty></entry>
</records>
XML
doc = Document.new(xml)
def doc_to_sqlite(doc, filename, table, inner_node_name)
db = SQLite3::Database.new(filename + '.db')
fields = XPath.match(doc.root, inner_node_name + '[1]/*').map{|node| node.name}
field_def = fields.map {|x| "%s TEXT" % x}.join(', ')
create = "create table %s (uid INTEGER PRIMARY KEY AUTOINCREMENT, %s)" % [table, field_def]
db.execute(create)
values = Array.new(fields.length, "'\%s'").join(', ')
insert = "insert into %s (%s) values (%s)" % [table, fields.join(', '), values]
doc.root.elements.each('entry') do |node|
sql_insert = insert % XPath.match(node, '*/text()')
db.execute(sql_insert)
end
db
end
doc_to_sqlite(doc, filename='company', 'company', inner_node_name='entry')
found this @http://webcache.googleusercontent.com/search?q=cache:RXkoLWIR8Q4J:snippets.rorbuilder.info/posts/show/873+ruby+convert+sqlite+to+xml&cd=4&hl=en&ct=clnk&gl=us&source=www.google.com
Created here for record keeping since the main site this pointed to is offline.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment