使用Nokogiri捕获XML响应

时间:2011-09-08 13:42:13

标签: ruby-on-rails nokogiri

我正在尝试一种功能,我获得成功的XML响应(一条消息)&失败(多个响应消息)但我无法使用nokogiri在我的rails代码中捕获这些消息以下是我在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

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

1 个答案:

答案 0 :(得分: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