gpt4 book ai didi

ruby - 在 Rails 3 中使用 Nokogiri 读取 XML 文件

转载 作者:数据小太阳 更新时间:2023-10-29 08:39:13 24 4
gpt4 key购买 nike

我在尝试遍历 XML 文件的一部分时遇到问题。我在 Rails3 中使用 Nokogiri。

我正在阅读这个 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")

这将导致与第一个相同的结果。

如果您对 namespace 不感兴趣,还有一种更简单的方法是使用 remove_namespaces! method :

doc.remove_namespaces!
doc.xpath("//Cube/Cube")

由于命名空间信息已被删除,此结果与前两个示例不太相同,但它会为您提供您期望的节点。

关于ruby - 在 Rails 3 中使用 Nokogiri 读取 XML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15068759/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com