Search code examples
xmlposthttpsruby-on-rails-2curb

Parsing Xml response from third party web service


I have installed cURB library for my rails 2 application and I am able to send multiple xml files to a single url of a web service as a post request. In addition to that I receive an receipt from the web service in an xml file which I need to be parsed by my application and out put the errors that have been created from the submitted file. Please could some one guide me with a good library and tutorial in capturing the response and parsing the xml document.

All suggestions are appreciated.


Solution

  • Unless you have already doing so, I recommend you use the libxml2 library for processing XML. The libxml2 library is available as a package on every major Linux distribution.

    gem install libxml-ruby
    

    What follows is a standalone example, that works with Rails 2.3.14, showing how to parse results from curb objects using an XML parser. It then demonstrates how to use XPath queries to select elements from the parsed XML document.

    require 'xml/libxml'
    require 'curb'
    
    # I have included this part so that this serves as a standalone example
    
    ce = Curl::Easy.new("http://www.myexperiment.org/announcements.xml")
    ce.perform
    
    # This is the part that deals with parsing the XML result
    
    doc = LibXML::XML::Parser.string(ce.body_str).parse
    
    # You can then use XPath queries to process the results, e.g.:
    
    doc.find("/announcements/announcement").each do |el|
      puts el.content
    end
    

    Complete documentation for libxml-ruby is available.