将带有ampersand-hash-char-semicolon字符的Ruby字符串转换为ascii或html友好字符串

gen*_*abs 3 ruby ruby-on-rails html-entities html-safe

使用Rails 3我正在使用drupal或其他东西生成的XML feed.它给我的标签看起来像:

<body><![CDATA[&#60;p&#62;This is a title&#60;br /&#62;A subheading&#60;/p&#62;]]></body>
Run Code Online (Sandbox Code Playgroud)

所以意图是这应该看起来像:

<p>This is a title<br />A subheading</p>
Run Code Online (Sandbox Code Playgroud)

这可能会在随后使用视图渲染<%= @mystring.html_safe %><%= raw @mystring %>什么的.麻烦的是以这种方式呈现字符串只会将子字符串&#60;转换为<字符.我需要一种双重原始或双重编码来首先处理chr,然后将标签渲染为html安全.

任何人都知道如下:

<%= @my_double_safed_string.html_safe.html_safe %>
Run Code Online (Sandbox Code Playgroud)

Bli*_*xxy 5

我不认为这是有效的XML - 它们通过使用实体 cdata 以两种不同的方式将文本两次转义.不过,您可以使用nokogiri解析它,例如:

require 'nokogiri'

xml = Nokogiri::XML.parse "<body><![CDATA[&#60;p&#62;This is a title&#60;br /&#62;A subheading&#60;/p&#62;]]></body>"
text = Nokogiri::XML.parse("<e>#{xml.text}</e>").text
#=> text = "<p>This is a title<br />A subheading</p>"
Run Code Online (Sandbox Code Playgroud)

看到这个drupal网站是疯狂的双重逃脱xml,我甚至倾向于使用正则表达式.黑客解决黑客创建的问题?IDK.而不管:

xml.text
#=> "&#60;p&#62;This is a title&#60;br /&#62;A subheading&#60;/p&#62;"
xml.text.gsub(/\&\#([0-9]+);/) { |i| $1.to_i.chr }
#=> "<p>This is a title<br />A subheading</p>"
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!