views:

90

answers:

4

I want to get a xml file, which I can request by an http request into an object. I'm looking for something similar to this (in a controller):

@ticket = request "http://example.com?ticketid=1234"

http://tickets.com?ticketid=1234 returns an XML (tickets.com is not the site the app is running on).

I then want to parse @ticket, to get the data out of the xml.

Thx a lot for all your help!

+2  A: 

If you just want to download the XML into a string, the following would do:

require 'open-uri'

xml = URI.parse("http://example.com?ticketid=1234").read

If you want to parse this XML and extract the data, you need to look at some kind of parser, e.g. LibXml or Nokogiri.

If you're trying to access data from another Rails application, maybe ActiveResource is the way to go. Here's a nice introduction.

Lars Haugseth
+1  A: 

Check out HTTParty for super easy consumption of web services. Basically, you'd do something like this:

class Ticket
  include HTTParty
  format :xml
end

@ticket = Ticket.get('http://url/to/ticket')

Then you can access elements in a hash:

@ticket['title'] # => the <title> element
Kyle Slattery
+1  A: 

Once you have the xml data you can use the Active Support Hash extension to convert it into a Hash

xml = URI.parse("http://example.com?ticketid=1234").read
data = Hash.from_xml(xml)

This way you don't need extra libs and figure out to traverse the xml. YMMV

Note: not sure how this method handles element attributes.

Henry
thx for the follow up tip!
Roland Studer
A: 

You can use Hpricot XML method like this:

require 'open-uri'
require 'hpricot'

@ticket = Hpricot.XML open "http://example.com?ticketid=1234"

Then you can easily parse @ticket with Hpricot dynamic methods. See some examples in the Hpricot page.

chmeee