Rails Note #10: Generating XML
This post should have made it a looong time ago..
I am currently building an application where all the output formats is in XML. One of the first problems I had was to output the xml.
- At first try, I could append ‘xml’ in the routes as a format parameter. But this takes into consideration that all our views would be in XML. However, you could have your views to be index.xml.erb or index.rxml, if you are using the builder templates plugin.
ActionController::Routing::Routes.draw do |map| #map.connect '/menu/show.xml', :controller => 'menu', :action => 'show', :format => 'xml' map.connect ':controller/:action/:id', :format => 'xml' map.connect ':controller/:action/:id.:format', :format => 'xml' end |
- If my application requires me to output both html and xml, then the above would not be sufficient. In my controller, I have to explicitly say :layout => false which means it would not use the application.html.erb found in app/views/layouts if we have one.
So far, I made progress using builder templates only but it is enough to suit my needs. Below is a sample controller and view.
app/controller/mobile_controller.rb
def index headers['Content-Type'] = 'text/xml; charset=utf-8' render :layout => false end |
app/views/index.rxml
xml.instruct! :xml, :version => "1.0", :encoding => "UTF-8" xml.content :type => "hypertext" do xml.head do xml.pageID "1" xml.title "USSD Page from Ruby" xml.protocol "html,java,wap,ussd,xhtml" end xml.body { greeting = 'Welcome back!' xml.p greeting } end |