Rails array to_xml
I have an array of user objects which I want to return as xml. How can I use to_xml to include attributes on the root element? For example
<users total="10">
<user>开发者_运维百科;
..
</user>
</users>
I know you can add custom elements and attributes to the xml using a block with the to_xml method, but I'm not sure how to add to the root element. Maybe there's another way other than using to_xml
I have used xml builder. Following code snippet covers some tricky xml building.
In you controller,
require 'builder'
def show_xml
@xml = get_xml_data
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @xml }
end
end
def get_xml_data
xml = Builder::XmlMarkup.new#(:target=>$stdout, :indent=>2)
xml.instruct! :xml, :version => "1.0", :encoding => "US-ASCII"
xml.declare! :DOCTYPE, :html, :PUBLIC, "-//W3C//DTD XHTML 1.0 Strict//EN",
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"
favorites = {
'candy' => 'Neccos', 'novel' => 'Empire of the Sun', 'holiday' => 'Easter'
}
xml.favorites do
favorites.each do | name, choice |
xml.favorite( choice, :item => name )
end
end
end
精彩评论