尝试使用nokogiri和xpath导航XML文件



我有一个xml文件,可以从以下位置下载:https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml

我想做的是浏览货币,这样我就可以把它们保存在我的数据库中。

我有:

open('app/assets/forex/eurofxref-daily.xml', 'wb') do |file|
file << open('https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml').read
end
then 
doc = File.open("app/assets/forex/eurofxref-daily.xml") { |f| Nokogiri::XML(f) }

我很难访问我感兴趣的节点来提取货币和价值。

我不熟悉Nokogiri,但在本教程中,您似乎可以应用以下XPath:/*/e:Cubes/e:Cube/e:Cube来选择所有Cube元素。

从那里,您可以迭代每个Cube元素,并选择它们的@currency@rate属性:

@doc = Nokogiri::XML(File.open("https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml"))
@doc.xpath('/*/e:Cubes/e:Cube/e:Cube', 'e' => 'ttp://www.ecb.int/vocabulary/2002-08-01/eurofxref').each do |node|
# do stuff
currency = node.attr('currency')
rate = node.attr('rate')      
end

最新更新