通过与Savon的SOAP调用,与Nokogiri一起阅读回复

时间:2012-02-28 12:38:57

标签: ruby-on-rails nokogiri savon

我和萨文打了一个肥皂电话。这工作正常,并给予 以下回复:

<?xml version="1.0" encoding="utf-8"?> 
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http:// 
schemas.xmlsoap.org/soap/envelope/"> 
  <soap:Body> 
    <GetTop10Response xmlns="http://www.kirupafx.com"> 
      <GetTop10Result> 
        <string>string</string> 
        <string>string</string> 
      </GetTop10Result> 
    </GetTop10Response> 
  </soap:Body> 
</soap:Envelope> 

现在我想从响应中取出所有字符串元素。但 我无法让它发挥作用。

def query(params=nil)

    client = Savon::Client.new do
      wsdl.document = "http://www.kirupafx.com/WebService/TopMovies.asmx?wsdl"
    end

    response = client.request :get_top10

    if response.success?
      xml = Nokogiri::XML(response.to_xml)
      print "Until here oké!"
      xml.search('//GetTop10Result').each do |result|
        print "How are you Ruby?"
        @result[result.at('string').inner_text] = result.at('string').inner_text
      end
    else
      raise "Error!"
end

但是他从不打印我漂亮的“你是红宝石怎么样?”有人可以帮忙 我?我做错了什么?

2 个答案:

答案 0 :(得分:2)

你可以这样做,但这不是处理这类问题的最佳方法!您可能有使用Nokogiri和XML的经验,但更容易使用这样的.to_hash

def query
    client = Savon::Client.new do
          wsdl.document = "http://www.kirupafx.com/WebService/TopMovies.asmx?wsdl"
    end
    response = client.request(:get_top10)
    response.to_hash[:get_top10_response][:get_top10_result] if response.success?
    false
end

答案 1 :(得分:0)

感谢您的反应!我想通了。这是我的代码:

# Prepare SOAP-request
client = Savon::Client.new do
  wsdl.document = "http://www.kirupafx.com/WebService/TopMovies.asmx?wsdl"
end

# Execute SOAP-request
response = client.request :get_top10

if response.success?
  names = Array.new(10)
  index = 0
  hash = response.to_hash[:get_top10_response][:get_top10_result][:string]
  hash.each do |value|
    names[index] = value
    index += 1
  end
  @result = {
    "0"=>{"name"=>"#{names.at(0)}"},
    "1"=>{"name"=>"#{names.at(1)}"},
    "2"=>{"name"=>"#{names.at(2)}"},
    "3"=>{"name"=>"#{names.at(3)}"},
    "4"=>{"name"=>"#{names.at(4)}"},
    "5"=>{"name"=>"#{names.at(5)}"},
    "6"=>{"name"=>"#{names.at(6)}"},
    "7"=>{"name"=>"#{names.at(7)}"},
    "8"=>{"name"=>"#{names.at(8)}"},
    "9"=>{"name"=>"#{names.at(9)}"}
  }
else
  raise "Error occurred during the request to the top 10 movies!"
end