Skip to content

Instantly share code, notes, and snippets.

@blaines

blaines/gist:203968

Created Oct 7, 2009
Embed
What would you like to do?
A recursive from_xml
def import
xml = open(params[:_]).read # Param for opening an XML file ( http://localhost/import?_=http://localhost/companies.xml )
doc = REXML::Document.new(xml)
@import = initialize_import(doc)
respond_to do |format|
format.html
end
end
# Process parent XML elements
def initialize_import(xml)
@array = Array.new
xml.elements.each do |e|
if e.size > 0 and e.attributes.get_attribute("type") and e.attributes.get_attribute("type").value.to_sym == :array
puts "Initialize #{e.name}"
e.elements.each do |ee|
puts " Initialized Import With #{ee.name.underscore.classify}"
model = ee.name.underscore.classify.constantize.new
ee.elements.each do |eee|
if eee.size > 0 and eee.attributes.get_attribute("type") and eee.attributes.get_attribute("type").value.to_sym == :array
puts " Process #{eee.name}"
process_import(eee,model)
elsif eee.size == 1
puts " Set Attribute #{eee.name} = #{eee.text}"
model[eee.name]= eee.text
end
end
@array << model
end
else
puts "FAILED TO INITIALIZE IMPORT"
end
end
return @array
end
# Process children XML elements
def process_import(xml,model)
h = Hash.new
xml.elements.each do |e|
puts " Enumerating #{e.name.underscore.pluralize}"
i = model.send(e.name.underscore.pluralize).build
e.elements.each do |ee|
if ee.size > 0 and ee.attributes.get_attribute("type") and ee.attributes.get_attribute("type").value.to_sym == :array
puts " Encountered Array #{ee.name}"
process_import(ee,i)
elsif ee.size == 1
puts " Set Attribute #{ee.name} = #{ee.text}"
i.send("#{ee.name.underscore}=", ee.text)
end
end
model
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment