开发者

How do I generate XML from XMLBuilder using a .xml.builder file?

I have started using xml builder templates for most of my model. I need to find a generic way to bu开发者_高级运维ild XML outside of a render which uses the .xml.builder template instead of the generic .to_xml method provided in the model

I gather that I will have to override the default to_xml (or add a to_my_xml), but I am unable to see how to get XMLBuilder to use my .builder files.

Any ideas?


Add a respond_to block in your controller so that the appropriate template is rendered according to the requested format. For example:

def show
  ...
  respond_to do |format|
    format.html # renders show.html.erb
    format.xml  # renders show.xml.builder
  end
end


If you are looking for how to create xml using builder then this is how you can do it

require 'rubygems'
require 'builder'
builder = Builder::XmlMarkup.new(:indent=>2)
builder.instruct! :xml, :version=>"1.0", :encoding=>"UTF-8"
builder.my_elements do |e|
  builder.myitem {|element| element.my_element_name('element_value')}
end

#=>

<?xml version="1.0" encoding="UTF-8"?>
<my_elements>
  <myitem>
    <my_element_name>element_value</my_element_name>
  </myitem>
</my_elements>


Hi I just had to solve this problem. Here is how I got it to work, comments inline ...

class PostsController < ApplicationController
  # this must be included to use tag helpers like cdata_block, etc ...
  include :Helpers::TagHelper

  def preview_xml
    @post = Post.find(params[:id])

    # You must set up a instance variable named 'xml'
    xml = ::Builder::XmlMarkup.new(indent: 2)

    builder_file = File.read(::Rails.root.to_s + '/app/views/posts/show.xml.builder')

    require 'builder'

    # instance_eval evaluates the file within the context of the current instance -- so the
    # xml variable we just set will be accessable within the builder_file
    instance_eval builder_file

    @tag_xml = xml.target!
  end

end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜