开发者

How do I navigate an XML file with Nokogiri?

Until now I've used this:

f = File.open("./Public/files/file.xml")
doc = Nokogiri::XML(f)
puts doc.at('conversionRate开发者_运维技巧Detail').text
f.close

And my XML sample is:

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

However, doc.at('conversionRateDetail') always returns 'nil'.


Your code for loading the file isn't done the Ruby way:

File.open("./Public/files/file.xml") do |f|
  doc = Nokogiri::XML(f)
  puts doc.at('conversionRateDetail').text
end

but that doesn't address why you are not able to access conversionRateDetail. Using 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                "

I'd recommend you use this instead though:

doc.at('conversionRateDetail currency').text # => "USD"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜