8th
How to parse XML in Rails with REXML
For example, we want to make a mashup site for our social life on the internet. Twitter, tumblr, flickr and so on. They often use xml but we are all moving more against a json world (that’s makes me happy) anyway…
To parse xml in Rails is quite easy actually. Lets go ahead and start develop our rails app by open the terminal and type:
rails mysociallife
cd mysociallife
Allright, we got a Rails application. Now we need to create a controller:
ruby script/generate controller fetch
Open up app/controllers/fetch_controller.rb in your favorite texteditor. First thing we need now is to import some packages we’ll going to use later on.
require ‘net/http’
require ‘rexml/document’
Lets say you want to fetch all your posts from your tumblr blog. The first thing you have to do is to check out there API. Its very easy to get data from a user. http://(your_login).tumblr.com returns an xml. Lets write some more code now. Begin to create a method namned all and paste the code.
def all
tumblr_url = “http://sweetsnippets.tumblr.com/api/read”
tumblr_xml = Net::HTTP.get_response(URI.parse(tumblr_url))
tumblr_doc = REXML::Document.new(tumblr_xml.body)
end
What actually happends here? The first line in the method is just a string so dont care about it. tumblr_xml is trying to get a respond in raw data and tumblr_doc is where the magic happends. REXML parse the data from tumblr_xml to a document. So far, so good. Now we got one problem. tumblr_doc is holding all data from my blog and its not what we wanted. Lets create an array that only holds the data we are intrested in.
@tumblr_posts = []
for post in tumblr_doc.elements.to_a(“//tumblr/posts/post[@type=’regular’]”)
@tumblr_posts « post.elements[‘regular-body’].text
end
Was it Woicke-speak? I only push data into the array that has one attribute called type=”regular”. See here if you want to learn more about xml. Dont forget .text because if you do the browser wont render html-tags correctly
Over to the view. Navigate to app/views/fetch and create a new file called all.html.erb and add this following lines.
<h1>My Social Life</h1>
<h1>Tumblr</h1>
<% for post in @tumblr_posts %>
<%= post %>
<% end %>
XML Parsing isn’t that hard! Very simple example but I hope you learned something. Happy coding!
