到目前为止,我一直用这个:

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)
    ---
    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

I am able to access 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"

09-27 15:56