Leon's Blogging

Coding blogging for hackers.

Outputting XML

| Comments

rails 當中,可以用 xml.builder 來輕鬆的輸出 xml

Format

可以直接在 routes ,設定 format 格式

1
get  :l, :defaults => { :format => 'xml' }

或是 controller

1
2
3
4
5
6
7
8
9
10
11
require 'csv'
class PeopleController < ApplicationController

def index
    @people = Person.all
    respond_to do |format|
      format.html
      format.json{ render :json => @person.to_json }
      format.xml { render :xml => @person.to_xml }
    end
end

View

index.xml.builder

1
2
3
4
5
6
7
8
9
10
11
12
13
14
xml.instruct!
xml.xml do
  xml.linkXml do
    xml.phone  @user
    xml.age    @age
  end
end

#<xml>
  #<linkXml>
    #<phone>1234-5678</phone>
    #<age>20</age>
  #</linkXml>
#</xml>

gem:
builder

參考文件:
Outputting XML Using Ruby on Rails Action View - 樣板設計

Comments