在生成的RSS提要中将内容编码为CDATA

  • 本文关键字:编码 CDATA RSS ruby rss cdata
  • 更新时间 :
  • 英文 :


我正在使用Ruby的内置RSS库生成RSS提要,该库在生成提要时似乎可以转义HTML。对于某些元素,我更希望它通过将其包装在CDATA块中来保留原始HTML。

一个最小的工作示例:

require 'rss/2.0'
feed = RSS::Rss.new("2.0")
feed.channel = RSS::Rss::Channel.new
feed.channel.title = "Title & Show"
feed.channel.link = "http://foo.net"
feed.channel.description = "<strong>Description</strong>"
item = RSS::Rss::Channel::Item.new
item.title = "Foo & Bar"
item.description = "<strong>About</strong>"
feed.channel.items << item
puts feed

它生成以下RSS:

<?xml version="1.0"?>
<rss version="2.0">
  <channel>
    <title>Title &amp; Show</title>
    <link>http://foo.net</link>
    <description>&lt;strong&gt;Description&lt;/strong&gt;</description>
    <item>
      <title>Foo &amp; Bar</title>
      <description>&lt;strong&gt;About&lt;/strong&gt;</description>
    </item>
  </channel>
</rss>

我希望保留原始HTML并将其封装在CDATA块中,而不是对频道和项目描述进行HTML编码,例如:

<description><![CDATA[<strong>Description</strong>]]></description>

monkey修补元素生成方法对我来说很有效:

require 'rss/2.0'
class RSS::Rss::Channel
  def description_element need_convert, indent
    markup = "#{indent}<description>"
    markup << "<![CDATA[#{@description}]]>"
    markup << "</description>"
    markup
  end
end
# ...

这阻止了对CCD_ 1的调用,该调用转义了一些特殊实体。

最新更新