简体   繁体   中英

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.

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)

您可以使用以下命令简单地呈现为xml(在您的控制器中):

render xml: @your_object

layout false, only: [:action]

This will remove all layout associated code.

On rails 5.2.x this is how you do it

class UserController < ApplicationController
  def view
    @user = User.find(params[:id])
    render formats: [:xml]
  end
end

With its corresponding view on app/views/user/view.xml

xml.User do
  xml.name @user.name
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM