到目前为止,我一直使用这个:
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"。
加载文件的代码不是用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(---警告:[]野村:1.5.0红宝石:版本:1.9.2平台:x86_64-darwin10.6.0说明:ruby 1.9.2p180(2011-02-18修订版30909([x86_64-darwin10.6.0]引擎:rubylibxml:绑定:扩展编译:2.7.3加载: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 USDn "
不过,我建议你使用这个:
doc.at('conversionRateDetail currency').text # => "USD"