2014-07-13 65 views
2

我使用Ruby的内置RSS库生成RSS源,这似乎在生成提要时转义HTML。对于某些元素,我更喜欢通过将其包装在CDATA块中来保留原始HTML。在生成的RSS源中将内容编码为CDATA

的最小工作示例:

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编码,信道和项目的描述,我想保持原始HTML并将它们包装在CDATA块中,例如:

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

回答

0

修补猴子the element-generating method部作品对我来说:

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 

# ... 

这样可以防止其逃脱了几个特殊实体调用Utils.html_escape

+0

这比我最终与之合作的解决方案更清洁,即使它是猴子补丁。 – Doches

+0

'class RSS :: Rss :: Channel :: Item'是在Ruby 2.3上为我工作的类。 – Todd