我试图使用Nokogiri从XML文件中获取一些数据,然后将其保存到数据库中。如何访问数组中的散列?
我正在使用的代码是:
def self.import_from_feed(feed)
doc = Nokogiri::XML(open(feed))
@products = doc.xpath('/merchantProductFeed/merchant/prod').map do |i|
{
'name' => i.xpath('text/name').inner_text,
'link' => i.xpath('uri/mLink').inner_text,
'description' => i.xpath('text/desc').inner_text,
'price' => i.xpath('price/buynow').inner_text
}
end
end
在Rails的控制台,我跑Products.import_from_feed(myfeedgoeshere)
,并得到:
[{"price"=>"8.00", "name"=>"BASIC GIRL BOXER", "description"=>"Boxer shorts Elasticated waist with Bench logo Button fly", "link"=>"http://www.bench.co.uk/womenswear/underwear/basic-girl-boxer/GY001X/"}, {"price"=>"10.00", "name"=>"CMTL PK SPORTY SOCKS", "description"=>"Ankle sockBench logo on sole of each sockContrasting stripe around ankle", "link"=>"http://www.bench.co.uk/womenswear/underwear/cmtl03593-3-pk-sporty-socks/BK014-SK034/"}, {"price"=>"12.00", "name"=>"A PK STRING UNDERWEAR", "description"=>"Plain thong Bench logo along waistband Bench tag on front", "link"=>"http://www.bench.co.uk/womenswear/underwear/a4771-3pk-string-underwear/PK023-BK001-WH001/"}, {"price"=>"8.00", "name"=>"BASIC GIRL BOXER", "description"=>"Boxer shorts Elasticated waist with Bench logo Button fly", "link"=>"http://www.bench.co.uk/womenswear/underwear/basic-girl-boxer/WH001/"}, {"price"=>"45.00", "name"=>"OSPREY TRAINER", "description"=>"Lace up trainers Bench logo on tongue and back of heelBench logo on end of trainer", "link"=>"http://www.bench.co.uk/menswear/footwear/osprey-trainer/WH001-BL081/"}, {"price"=>"45.00", "name"=>"OSPREY TRAINER", "description"=>"Lace up trainers Bench logo on tongue and back of heelBench logo on said of trainer", "link"=>"http://www.bench.co.uk/menswear/footwear/osprey-trainer/WH001-GR128/"}, {"price"=>"90.00", "name"=>"META TRENCH", "description"=>"Vintage look leather bootLace upFabric sidesPull on tab on heel", "link"=>"http://www.bench.co.uk/womenswear/footwear/meta-trench/BK001/"}]
(^ Truncated)
有人能告诉我怎样才能访问数组中的元素?环通所以我可以得到@products.price
,@products.description
等?
编辑:我试过@products[0]
,products[0]
,我试过打印键/值对没有任何运气。
我不是要求你做所有的工作,我认为这里有几个概念在工作 - 足以让我打砖墙。
第2部分:额外信贷!
根据选定的答案,这应该工作,对吧?
@products.each do |h|
h.save
end
我得到:
NoMethodError: undefined method `save' for #<Hash:0x10388c7d8>
感谢您的回答,现在就编辑。澄清 - theres a)价格后失踪,对吧? – 2011-04-26 20:42:27
它的工作!非常感谢!我不能投你的答案(代表<15),我会尽我所能回复它。 – 2011-04-26 20:44:57
@Geoff,感谢您收集错误。我不应该在第一杯咖啡之前给出答案! – buruzaemon 2011-04-26 20:47:57