2014-06-06 83 views
1

我想使用Nokogiri解析一个HTML片段,对它做些什么,然后将有效的HTML写入文件。Nokogiri write_html_to奇怪?

这似乎很容易,但我很困惑为什么Nokogiri的doc.write_html_to方法是将我的片段包装在一个空的元素标记括号内。

# Try this in IRB 
doc = Nokogiri::HTML.fragment('<h1 id="foo">Hello</h1>') 

# Option #1 - Wrapped in Empty Tag 
doc.write_html_to(File.new('write_html_to.html', 'w'), :encoding => 'UTF-8') 
# => <><h1 id="foo">Hello</h1></> 

# Option #2 - Works as needed 
File.open('doc_to_html.html', 'w'){|f| f.write(doc.to_html(:encoding => 'UTF-8'))} 
# => <h1 id="foo">Hello</h1> 

任何想法为什么选项#1将HTML片段文件封装在空标记中?

+0

你其报告为一个错误?否则,我可以做同样的事情。 –

回答

1

在编写Nokogiri::HTML::DocumentFragment时,它似乎是执行Node#write_html_to时的一个错误。我发现,write_xhtml_to正常工作:

doc.write_xhtml_to(File.new('write_xhtml_to.html', 'w'), :encoding => 'UTF-8') 

# => <h1 id="foo">Hello</h1> 
+0

感谢您的反馈,我将在GitHub上添加一个问题。 – Eric

1

我一直使用File.write为单行写。这将会是仅仅比使用File.open与块一样便利使用引入nokogiri的write_html_to,以及更短:

require 'nokogiri' 

doc = Nokogiri::HTML.fragment('<h1 id="foo">Hello</h1>') 
File.write('write_html_to.html', doc.to_html(encoding: 'UTF-8')) 
+0

感谢Ruby的简洁提示,但并不真正解决Nokogiri问题。 – Eric

+0

这是一个错误。在解决问题时报告它。我会用更短的方法解决它。 –