我試圖使用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