到现在为止我已经用过了:
f = File.open("./Public/files/file.xml")
doc = Nokogiri::XML(f)
puts doc.at('conversionRateDetail').text
f.close
我的XML示例是:
<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Header>
</soap:Header>
<soap:Body>
<Fare_MasterPricerCalendarReply>
<replyStatus>
<status>
<advisoryTypeInfo>123</advisoryTypeInfo>
</status>
</replyStatus>
<conversionRate>
<conversionRateDetail>
<currency>USD</currency>
</conversionRateDetail>
</conversionRate>
</Fare_MasterPricerCalendarReply>
</soap:Body>
</soap:Envelope>
但是,doc.at('conversionRateDetail')
始终返回'nil'。
答案 0 :(得分:2)
加载文件的代码不是以Ruby方式完成的:
File.open("./Public/files/file.xml") do |f|
doc = Nokogiri::XML(f)
puts doc.at('conversionRateDetail').text
end
但这并不能解决您无法访问conversionRateDetail
的原因。使用nokogiri -v
...
# Nokogiri (1.5.0) --- warnings: [] nokogiri: 1.5.0 ruby: version: 1.9.2 platform: x86_64-darwin10.6.0 description: ruby 1.9.2p180 (2011-02-18 revision 30909) [x86_64-darwin10.6.0] engine: ruby libxml: binding: extension compiled: 2.7.3 loaded: 2.7.3
我可以访问conversionRateDetail
:
xml = <<EOT
<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Header>
</soap:Header>
<soap:Body>
<Fare_MasterPricerCalendarReply>
<replyStatus>
<status>
<advisoryTypeInfo>123</advisoryTypeInfo>
</status>
</replyStatus>
<conversionRate>
<conversionRateDetail>
<currency>USD</currency>
</conversionRateDetail>
</conversionRate>
</Fare_MasterPricerCalendarReply>
</soap:Body>
</soap:Envelope>
EOT
require 'nokogiri'
doc = Nokogiri::XML(xml)
doc.at('conversionRateDetail').text # => "\n USD\n "
我建议你改用它:
doc.at('conversionRateDetail currency').text # => "USD"