 <p>I use following code fix:</p> <pre><code>require 'nokogiri' d = Nokogiri::HTML(%Q(&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;/head&gt; &lt;body&gt; &lt;/body&gt; &lt;/html&gt; )) d.css('body')[0].add_child(Nokogiri::XML::Comment.new(d, "doc")) puts d.to_s </code></pre>