Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails - to_xml placing values in xml attributes not tags

Suppose I have a controller method like so...

def index
  @burried_treasures = BurriedTreasure.all
  render :xml => @burried_treasure
end

Right now it places all values in tags such as:

<burried_treasure>
  <name>Red Beard</name>
</burried_treasure>

I would like it to use attributes like this:

<burried_treasure name="Red Beard">

Does anyone know how to accomplish this?

like image 680
WoodenKitty Avatar asked Jan 28 '11 04:01

WoodenKitty


1 Answers

You will have to override your models to_xml method

class BurriedTreasure < ActiveRecord::Base
    def to_xml(options = {})
      options[:indent] ||= 2
      xml = options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent])
      xml.instruct! unless options[:skip_instruct]
      xml.buried_treasure('name' => self.name)
      xml.some_nodes do |some_node|
            some_node.some_level2_node "some_level_2_node_content"
      end   
    end
  end

See more info on Builder::XmlMarkup usage at http://ap.rubyonrails.org/classes/Builder/XmlMarkup.html

like image 184
Vlad Gurovich Avatar answered Oct 04 '22 04:10

Vlad Gurovich