2011-08-30 30 views
0

我試圖驗證登錄過程中,在我登錄過程中如果用戶名&密碼正確,那麼用戶將登錄到他的儀表板,但如果用戶名爲&,密碼爲錯了,我得到一個XML響應。在rails中使用Nokogiri捕獲XML響應3.0.9

以下是session_controller代碼

{

require 'net/http' 
require 'uri' 
require 'open-uri' 
require 'nokogiri' 
class SessionsController < ApplicationController 
def new 
@title = "Sign in" 

end 

def create 

    redirect_to "http://<SERVER_IP>/billing/api/login?u=#{params[:session][:email]}&p=#{params[:session][:password]}" 

a = "http://<SERVER_IP>/billing/api/login?u=#{params[:session][:email]}&p=#{params[:session][:password]}" 

doc = Nokogiri::XML(open(a).read) 
    doc.css('status').each do |link| 


    # Create error message and re-render signin page 

@b = link.content 


end 
end 

def destroy 
    sign_out 
    redirect_to root_path 
end 
end 

}

我得到這樣的XML響應從服務器

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<action> 
<name>login</name> 
<status>failed</status> 
<status_message>Error description</status_message> 
</action> 

那些我得到這個反應我想使用上面的XML響應來刷新錯誤消息。

如果任何人有任何想法會拯救我的一天。

回答

0

嘿人我終於上述functionality.That做是不是因爲我想給其他用戶,我在這裏粘貼確切的片斷大量艱鉅

def create 

a = "http://<SERVER IP>/billing/api/login?u=#{params[:session][:email]}&p=#{params[:session][:password]}" 

# Nokogiri Gem is used to Catch the XML response from the MOR & call the appropriate action on the received status 

    doc = Nokogiri::XML(open(a)) 
    doc.xpath('/action/status').each do |link| 
    @abc = link.content 
    end 

    # Condition to check whether the received response is 'Ok' or 'Failed' 

    if @abc == 'failed' 

      flash[:notice] = "Invalid Username/Password" # If condition is failed redirect to root page 
      redirect_to '/' 
      else 
       # if condition is 'ok' redirect to MOR user dashboard 

       redirect_to "http://<SERVER IP>/billing/api/login?u=#{params[:session][:email]}&p=#{params[:session][:password]}" 
     end           

0

引入nokogiri爲您提供了直接訪問到文檔的文本:

require 'nokogiri' 

doc = Nokogiri::XML(
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<action> 
<name>login</name> 
<status>failed</status> 
<status_message>Error description</status_message> 
</action>' 
) 

irb你會看到:

doc.text 

>> "\nlogin\nfailed\nError description\n" 

您可以簡化您的代碼是這樣的:

doc = Nokogiri::XML(open(a)) 

if doc.text['failed'] 
    ...