用builder写xml

很简单,Builder负责生成xml,通过ruby的io输出到指定xml文件。
代码:

require 'builder'

Person=Struct.new("Person",:name,:age)
people=[]
people << Person.new("a",33)
people << Person.new("b",22)
xml=Builder::XmlMarkup.new :indent=>1
xml.instruct!
xml.people do
people.each do |p|
xml.person do
xml.name p.name
xml.age p.age
end
end
end


xml_str=xml.target!
open('people.xml','w') do |f|
f.puts xml_str
end


输出:

<?xml version="1.0" encoding="UTF-8"?>
<people>
<person>
<name>a</name>
<age>33</age>
</person>
<person>
<name>b</name>
<age>22</age>
</person>
</people>
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页