Ruby Builder - XML输出编码HTML实体

时间:2011-03-23 11:41:00

标签: html ruby xml unicode entities

我有一个使用Builder的小ruby脚本。

require 'rubygems'
require 'builder'

content = <<eos
SOME TEXT, GOES TO UPPERCASE
other text
<em>italics<em>
eos

xml = Builder::XmlMarkup.new
  xml.instruct! :xml, :version => '1.0'
  xml.book :id => 1.0 do
    xml.keyPic "keyPic1.jpg"
    xml.parts do
      xml.part :partId => "1", :name => "name" do
        xml.chapter :title => "title", :subtitle => "subtitle" do
          xml.text content
        end
      end
    end
  end

p xml

从CLI(Cygwin)运行时,我得到以下内容:

<?xml version="1.0" encoding="UTF-8"?>
<book id="1.0">
  <keyPic>keyPic1.jpg</keyPic>
    <parts>
      <part partId="1" name="name">
        <chapter title="title" subtitle="subtitle">
          <text>
          SOME TEXT, GOES TO UPPERCASE
          other text
          &lt;em&gt;italics&lt;em&gt;
          </text>
        </chapter>
      </part>
    </parts>
</book><inspect/>

但是,我想要的输出是:

<text>
SOME TEXT, GOES TO UPPERCASE
other text
<em>italics<em/>
</text>

我曾尝试使用htmlentities gem'解码'内容,但无济于事。

1 个答案:

答案 0 :(得分:6)

使用<<操作无需修改即可插入文本。

xml.text do |t|
  t << content
end