我在尝试循环访问 XML 文件的一部分时遇到问题。我将 Nokogiri 与 Rails3 结合使用。
我正在阅读此 XML 提要 - http://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist-90d.xml
这是我的代码:
def save_rates
# get the XML data form ECB URL
file_handle = open('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist-90d.xml')
# get document xml string and create Nokogiri object
doc = Nokogiri::XML(file_handle)
# foreach date...
doc.xpath("//Cube/Cube").each do |cube|
raise cube.inspect # isn't being executed
# foreach currency...
cube.xpath("./Cube").each do |curr|
# create DB entry
Exchange.create(:currency=>curr.currency, :rate=>curr.rate, :record_date => cube.time)
end
end
end
当我检查 doc
时,我可以看到 Nokogiri 对象。但是,当我尝试在第一个 .each 循环内引发 cube.inspect
时,它只是没有触发。所以这让我相信我的道路是错误的://Cube/Cube
。
从我在 Nokogiri 教程中看到的其他示例中,路径与此类似。是我的路径错误还是我在这里做错了什么?
我是 ruby n00b,所以请放轻松!
更新
这是 XML 的格式
<gesmes:Envelope xmlns:gesmes="http://www.gesmes.org/xml/2002-08-01" xmlns="http://www.ecb.int/vocabulary/2002-08-01/eurofxref">
<gesmes:subject>Reference rates</gesmes:subject>
<gesmes:Sender>
<gesmes:name>European Central Bank</gesmes:name>
</gesmes:Sender>
<Cube>
<Cube time="2013-02-25">
<Cube currency="USD" rate="1.3304"/>
<Cube currency="JPY" rate="125"/>
<Cube currency="BGN" rate="1.9558"/>
<Cube currency="CZK" rate="25.52"/>
<Cube currency="DKK" rate="7.4614"/>
<Cube currency="GBP" rate="0.8789"/>
...
</Cube>
<Cube>
<Cube time="2013-02-24">
<Cube currency="USD" rate="1.3304"/>
<Cube currency="JPY" rate="125"/>
<Cube currency="BGN" rate="1.9558"/>
<Cube currency="CZK" rate="25.52"/>
<Cube currency="DKK" rate="7.4614"/>
<Cube currency="GBP" rate="0.8789"/>
...
</Cube>
</Cube>
</gesmes:Envelope>
最佳答案
这里的问题是由于 XML namespaces .
在 XML 的根属性中,有一个属性 xmlns="http://www.ecb.int/vocabulary/2002-08-01/eurofxref"
,它指定默认命名空间。 Cube
元素位于此命名空间中,如果您仅使用 Cube
而不指定命名空间,则不会获得匹配项。
要在 Nokogiri 中指定命名空间,您可以执行以下操作:
doc.xpath("//ecb:Cube/ecb:Cube", 'ecb' => "http://www.ecb.int/vocabulary/2002-08-01/eurofxref")
在这里,我们为命名空间指定了前缀 ecb
,并在 XPath 表达式中使用该前缀。
在这种情况下,命名空间是在根节点上声明的默认命名空间,Nokogiri 将为我们在 xmlns
前缀上声明它,因此我们可以使用更简单的:
doc.xpath("//xmlns:Cube/xmlns:Cube")
这将导致与第一个相同的结果。
如果您对命名空间不感兴趣,还有一种更简单的方法是使用 remove_namespaces!
method :
doc.remove_namespaces!
doc.xpath("//Cube/Cube")
由于 namespace 信息已被删除,此结果与前两个示例不太相同,但它会为您提供所需的节点。
关于ruby - 在 Rails 3 中使用 Nokogiri 读取 XML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15068759/