使用Nokogiri更换时的编码问题

问题描述:

我有这个代码:

# encoding: utf-8
require 'nokogiri'

s = "<a href='/path/to/file'>Café Verona</a>".encode('UTF-8')
puts "Original string: #{s}"

@doc = Nokogiri::HTML::DocumentFragment.parse(s)

links = @doc.css('a')
only_text = 'Café Verona'.encode('UTF-8')
puts "Replacement text: #{only_text}"
links.first.replace(only_text)
puts @doc.to_html

但是,输出是:

Original string: <a href='/path/to/file'>Café Verona</a>
Replacement text: Café Verona
Café Verona

@doc 最后是错误的编码?

'UTF-8')或使用文档而不是 DocumentFragment 问题。

I tried with and without encode('UTF-8') or using Document instead of DocumentFragment, but it's the same problem.

我在Ruby 1.9.3p194上使用Nokogiri v1.5.6。

I'm using Nokogiri v1.5.6 with Ruby 1.9.3p194.

似乎如果你通过一个nokogiri文本对象它做的事);

Seems that if you pass a nokogiri text object it does the thing ;)

links.first.replace Nokogiri::XML::Text.new(only_text, @doc)