Over a million developers have joined DZone.

XML Attributes To Database Columns

I recently needed to update a database with the contents of an XML file under a controlled environment (details at Blackrat's Blog) and came up with this. 

With an XML input file of the following format


and a database which contains identical columns name,desc,other (or a superset of the tags) you can use the follow snippet to populate it. 

View [import_xml.rhtml]

Import XML

<%= form_tag({ :action => 'import_xml'}, { :multipart => true }) %> <%= file_field 'document', 'file' %> <%= submit_tag 'Import' %> <%= end_form_tag %>
Controller [names_controller.rb] def import_xml require 'rexml/document' file=params[:document][:file] doc=REXML::Document.new(file.read) doc.root.each_element('//tag') do |tag| @name = Name.new @name.update_attributes(tag.attributes) end redirect_to :action => 'list' end

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}