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

时间:2018-12-01 18:51:06

标签: ruby-on-rails xpath nokogiri

我有一个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) }

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

1 个答案:

答案 0 :(得分:0)

我不熟悉Nokogiri,但是from this tutorial似乎可以应用以下XPath: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 属性:

mergeAll()