2011-03-11 2 views
1

xml로 반환하려는 사용자 개체의 배열이 있습니다. to_xml을 사용하여 루트 요소에 특성을 포함하려면 어떻게해야합니까? 예를레일 배열 to_xml

<users total="10"> 
     <user> 
     .. 
     </user> 
    </users> 

를 들어 당신이 사용자 지정 요소를 추가하고 to_xml 방법으로 블록을 사용하여 XML 속성을 수있어,하지만 난 루트 요소에 추가하는 방법을 모르겠어요. 어쩌면 to_xml을 사용하는 것 외의 다른 방법이있을 수도 있습니다.

답변

1

xml 빌더를 사용했습니다. 다음 코드 스 니펫은 까다로운 xml 빌드를 다룹니다. 당신이 컨트롤러에서

,

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