如何防止Nokogiri编码HTML片段中的实体

时间:2012-02-29 01:44:09

标签: html ruby nokogiri html-entities

Nokogiri 1.5.0

我无法输出带有查询参数的链接的解析片段,特别是href中的&符号。 &符号由其html实体替换。

f = Nokogiri::HTML.fragment(%q{<a href="http://example.com?this=1&that=2">Testing</a>})
f.to_s    # => "<a href=\"http://example.com?this=1&amp;that=2\">Testing</a>"
f.to_html # => "<a href=\"http://example.com?this=1&amp;that=2\">Testing</a>"

使用to_html(encoding: 'UTF-8')或US-ASCII无法提供帮助。

这似乎很常见,解析有效的链接格式并希望将其呈现为有效的HTML。

How to make Nokogiri transparently return un/encoded Html entities untouched?没有帮助。

1 个答案:

答案 0 :(得分:4)

Nokogiri的HTML解析器会自动更正源文档中的错误。 URL中的裸露&符号为actually an error,因此Nokogiri正在纠正它。如果您查看f.errors,您会发现它不认为&that是一个有效的实体并且缺少分号,因此它将&符号修复为&amp;,使其有效HTML。