DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

XML Attributes To Database Columns

  • submit to reddit
        I recently needed to update a database with the contents of an XML file under a controlled environment (details at <a href="">Blackrat's Blog</a>) and came up with this. 

With an XML input file of the following format
  <tag name='test' desc='Test Description' other='Other Item' />
  <tag name='test2' desc='2nd Test Description' other='Another Item' />

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]
<h1>Import XML</h1>

<%= 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'
  doc.root.each_element('//tag') do |tag|
    @name =
  redirect_to :action => 'list'