Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encoding issue when using Nokogiri replace

I have this code:

# 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

However, the output is this:

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

Why does the text in @doc end up with the wrong encoding?

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

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

like image 577
Cristian Avatar asked Feb 28 '13 21:02

Cristian


1 Answers

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

links.first.replace Nokogiri::XML::Text.new(only_text, @doc)
like image 111
Ismael Avatar answered Nov 15 '22 07:11

Ismael