2011-09-08 58 views
0

我正在嘗試獲取成功的一個XML響應的函數(一條消息)&失敗(多個響應消息),但我無法使用nokogiri在我的rails代碼中捕獲這些消息我在XML響應使用Nokogiri捕獲XML響應

對於失敗的方面得到的消息(我能得到太多其他故障消息)

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<status> 
    <error> Such username is allready taken </error> 
</status> 

成功(這是唯一的反應)

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<status> 
    <success>Registration succesful</success> 
</status> 

在我的代碼我想如果有什麼想法,將節省我一天做以下

def create 

    @user = User.new(params[:user]) 


    a = "https://www.example.com"  

    url = URI.parse(a) 
     http = Net::HTTP.new(url.host, url.port) 
     http.use_ssl = true if url.port == 443 
     http.verify_mode = OpenSSL::SSL::VERIFY_NONE if url.port == 443 
     path = url.path + "?" + "request_query" 
     res, data = http.get(path) 

     case res 
     when Net::HTTPSuccess, Net::HTTPRedirection 
      doc = Nokogiri::XML(data) 

      doc.xpath('/status/success').each do |link| 
      @abc = link.content 
      end 

       flash[:notice] = @abc 

      if @abc == 'Registration successful' 
       flash[:notice] = "Registration successful" 

      redirect_to "/" 



      else 
      doc.xpath('/status/error').each do |link| 
      @err = link.content 
      end 

      flash[:notice] = @err 
      render "new"  

    end 
end 

中的任何一個。

回答

0

這可以幫助你。

case res 
    when Net::HTTPSuccess, Net::HTTPRedirection 
    @doc = Nokogiri::XML(data) 

    @doc.xpath('/status/success').each do |oop| 
     @ee = oop.content 
    end 

    if @ee.nil? 
     @doc.xpath('/status/error').each do |link| 
      @status = link.content 
     end 

     flash[:notice] = @status 
     render "new" 
    else 
     flash[:notice] = @ee 
     redirect_to "/" 
    end 
end 
+0

謝謝它現在工作。 – Anup