在rails 3.0.9中使用Nokogiri捕获XML响应

时间:2011-08-30 10:32:19

标签: ruby-on-rails nokogiri

我正在尝试验证登录过程,在我的登录过程中,如果用户名&密码是正确的,然后用户将登录到他的仪表板,但如果用户名&密码错了然后我得到一个XML响应。

以下是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响应来刷新错误消息。

如果有任何想法会节省我的一天。

2 个答案:

答案 0 :(得分:0)

Hey Folks我终于完成了上述功能。这对于其他用户我认为没有太多困难我在这里粘贴了确切的片段

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                                        

结束

答案 1 :(得分: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']
  ...