rails - to_xml将值放在xml属性中而不是标记中

时间:2011-01-28 04:50:17

标签: ruby-on-rails ruby xml xml-serialization

假设我有一个像这样的控制器方法......

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

现在它将所有值都放在标签中,例如:

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

我希望它使用这样的属性:

<burried_treasure name="Red Beard">

有谁知道如何做到这一点?

1 个答案:

答案 0 :(得分:5)

您必须覆盖模型to_xml方法

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

http://ap.rubyonrails.org/classes/Builder/XmlMarkup.html

上查看有关Builder :: XmlMarkup用法的更多信息