Search code examples
ruby-on-railsxmlrendering

Can I respond with XML to an HTML request in Rails?


I want to put in a simple API that responds to a GET request with a query string. But I want to return XML, not HTML.

I would even like to test this in the browser so that if I key in the URL and the query string, then see the XML in the response.

I just about have it by rendering :text, but my xml is doing two things:

1. All tag names are being downcased.

2. My xml is being wrapped in an HTML container (HTML, HEAD, BODY, etc.)

I just need to get rid of that HTML wrapper.


Solution

  • This one works for me:

    respond_to do |format|
      format.xml do
        headers['Content-Disposition'] = 'attachment;filename="katalog.xml"'
        render :xml => xml_array.to_xml(:skip_types => true, :root => "Items"),
               :layout => false,
               :content_type => Mime::XML
      end
    end
    

    You should be able to replace xml_array.to_xml(:skip_types => true, :root => "Items") with your string, since .to_xml doesn't do anything else but generating a string (and making sure it's proper XML)