简体   繁体   English

我可以在Rails中以XML响应HTML请求吗?

[英]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. 我想放入一个简单的API,该API用查询字符串响应GET请求。 But I want to return XML, not HTML. 但是我想返回XML,而不是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. 我什至想在浏览器中对此进行测试,以便如果我键入URL和查询字符串,然后在响应中看到XML。

I just about have it by rendering :text , but my xml is doing two things: 我只是通过渲染:text拥有它,但是我的xml正在做两件事:

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. 我只需要摆脱那个HTML包装器。

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_array.to_xml(:skip_types => true, :root => "Items") ,因为.to_xml除了生成字符串(并确保它是正确的XML)之外,不会做其他任何事情

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

render xml: @your_object

layout false, only: [:action] 布局错误,仅:[:action]

This will remove all layout associated code. 这将删除所有与布局相关的代码。

On rails 5.2.x this is how you do it 在Rails 5.2.x上,这是您的操作方式

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 在app / views / user / view.xml中具有其相应的视图

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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