有这么段代码解析xml文件后,将数据存入数据库表里面。有多个xml文件,每个文件对应一个表
def diming
f=File.new("L:/newapp/zonghe/app/views/zonghe/diming.xml")
doc = REXML::Document.new(f)
doc.elements.each("*/Document/Placemark") do |element|
country=Country.new
xuhao=element.attributes["id"]
name=element.elements["name"].text
country.xuhao=xuhao
country.name=name
lng,lat=element.elements["Point/coordinates"].text.split(',') #
country.lng=lng
country.lat=lat
country.save
end
end
有几个问题:1.如过用函数调用的方法,把xml文件当参数传进去,这段代码修改后应该放在rails工程的哪个目录下?
2.因为每个xml文件对应一个类,所以model也要作为参数传进去。如何把类作为参数?
3.我想在console下调用函数。
请大家给我点详细的思路。
[quote]3.我想在console下调用函数[/quote]
你应该做成rake
[quote]1.如过用函数调用的方法,把xml文件当参数传进去,这段代码修改后应该放在rails工程的哪个目录下? [/quote]
rake代码放在lib/tasks下
[quote]2.因为每个xml文件对应一个类,所以model也要作为参数传进去。如何把类作为参数? [/quote]
model是你app的一部分 load它就可以在rake里面用了 类名本质上是一个全局常量
这样写如何 放在具体的model类里面~
也可以放在applicationController中....
[code="ruby"]
def dined(file,filename)
if filename.is_a?(String)
file = File.new(filename)
end
if file.is_a?(File)
doc = REXML::Document.new(file)
doc.elements.each("*/Document/Placemark") do |element|
country=Country.new
xuhao=element.attributes["id"]
name=element.elements["name"].text
country.xuhao=xuhao
country.name=name
lng,lat=element.elements["Point/coordinates"].text.split(',') #
country.lng=lng
country.lat=lat
country.save
end
end
end
[/code]
吧类作为参数就像上述的代码一样不是可以吗?
放在lib里面,嘿嘿
我理解你的意思是一种xml文件对应一个model,那么这个方法就应该放在model里面,
每个model里都要有样一个方法,写成类方法比较方便。
另外,因为每个模型都不一样,所以做成一个通用方法没有意义。
[code="java"]
def self.create_from_xml(file)
f=File.new("L:/newapp/zonghe/app/views/zonghe/diming.xml")
doc = REXML::Document.new(f)
doc.elements.each("*/Document/Placemark") do |element|
country=Country.new
xuhao=element.attributes["id"]
name=element.elements["name"].text
country.xuhao=xuhao
country.name=name
lng,lat=element.elements["Point/coordinates"].text.split(',') #
country.lng=lng
country.lat=lat
country.save
end[/code]