2014-06-06 59 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

這是一個錯誤。在解決問題時報告它。我會用更短的方法解決它。 –