7

如何在未触及 html 实体(如德语变音符号)的情况下使用 Nokogiri?

IE:

# this is fine
node = Nokogiri::HTML.fragment('<p>&ouml;</p>')
node.to_s # => '<p>&ouml;</p>'

# this is not
node = Nokogiri::HTML.fragment('<p>ö</p>')
node.to_s # => '<p>&ouml;</p>'

# this is what I need
node = Nokogiri::HTML.fragment('<p>ö</p>')
node.to_s # => '<p>ö</p>'

我试图弄乱 PARSE_OPTIONS 和 :save_with 选项,但无法想出让 Nokogiri 像上面一样透明地表现的方法。

任何指针?

4

1 回答 1

12

好的,Aaron 通过twitter / gist回答了我的问题:

require 'rubygems'
require 'nokogiri'

doc = Nokogiri::HTML::Document.new
doc.encoding = 'UTF-8'

# We added a contextual fragment method for the 1.4.2 release. This *might*
# work in 1.4.1. If you want to mess with 1.4.2, build from my github, or
# grab one of our nightly builds:
#
# $ sudo gem install nokogiri -s http://tenderlovemaking.com/
#
# Also, libxml2 had a bug with encoding when handling UTF-8 fragments, so I
# suggest you also upgrade to libxml2 2.7.7.
#
# Hope that helps!
puts doc.fragment('<p>ö</p>')
于 2010-04-02T16:51:46.237 回答