Jim WeirichBuilder提供了一个简单的方法创建XML标记和数据结构。

xml

Builder::XmlMarkup::生成XML标记,Builder::XmlEvents::生成XML事件。

用法

require 'rubygems'
  require_gem 'builder', '~> 2.0'

  builder = Builder::XmlMarkup.new
  xml = builder.person { |b| b.name("Jim"); b.phone("555-1234") }
  xml #=> <person><name>Jim</name><phone>555-1234</phone></person>

require 'rubygems'
  require_gem 'builder'

  builder = Builder::XmlMarkup.new(:target=>STDOUT, :indent=>2)
  builder.person { |b| b.name("Jim"); b.phone("555-1234") }
  #
  # 打印:
  # <person>
  #   <name>Jim</name>
  #   <phone>555-1234</phone>
  # </person>

特性

支持XML注释

xml_markup.comment! "This is a comment"
  #=>  <!-- This is a comment -->

也支持XML处理指令

xml_markup.instruct! :xml, :version=>"1.0", :encoding=>"UTF-8"
  #=>  <?xml version="1.0" encoding="UTF-8"?>

部分支持XML entity声明

xml_markup.declare! :DOCTYPE, :chapter, :SYSTEM, "../dtds/chapter.dtd"
  #=>  <!DOCTYPE chapter SYSTEM "../dtds/chapter.dtd">

可以嵌套声明

@xml_markup.declare! :DOCTYPE, :chapter do |x|
  x.declare! :ELEMENT, :chapter, :"(title,para+)"
  x.declare! :ELEMENT, :title, :"(#PCDATA)"
  x.declare! :ELEMENT, :para, :"(#PCDATA)"
end

#=>

<!DOCTYPE chapter [
  <!ELEMENT chapter (title,para+)>
  <!ELEMENT title (#PCDATA)>
  <!ELEMENT para (#PCDATA)>
]>

XML命名空间

xml.SOAP :Envelope do ... end

默认情况下特殊字符会自动转义:

xml = Builder::XmlMarkup.new
xml.sample(:escaped=>"This&That", :unescaped=>:"Here&amp;There")
xml.target!  =>
  <sample escaped="This&amp;That" unescaped="Here&amp;There"/>

如果不想转义,请使用符号代替字符串。

支持UTF-8

$KCODE = 'UTF8'
xml = Builder::Markup.new
xml.instruct!(:xml, :encoding => "UTF-8")
xml.sample("Iñtërnâtiônàl")
xml.target!  =>
  "<sample>Iñtërnâtiônàl</sample>"

GitHub页面

Jim Weirich


编译 SegmentFault


weakish
24.6k 声望844 粉丝

a vigorously lazy deadbeat with matured immaturity