zetafish zetafish - 4 months ago 24
Ruby Question

How to add a comment with Nokogiri Builder

How do I add a

<!-- blahblah -->
comment to XML with Nokogiri's Builder?

I want to have something like:

<root>
<!--blahblah-->
<child/>
</root>


I try something like this:

Nokogiri::XML::Builder.new do |xml|
xml.root {
xml.comment('blahblah')
xml.child
}
end


But that gives me:

<root>
<comment>blahblah</comment>
<child/>
</root>

Answer

You can work around this bug documented future feature not present in the current release by using Builder#<< as follows:

require 'nokogiri'

xml = Nokogiri::XML::Builder.new do |xml|
  xml.root {
    xml << '<!--blahblah-->'
    xml.child
  }
end

puts xml.doc.root.to_xml
#=> <root>
#=>   <!--blahblah-->
#=>   <child/>
#=> </root>

Alternatively, you can monkeypatch in your own version of the future method:

class Nokogiri::XML::Builder
  def comment(string)
    insert Nokogiri::XML::Comment.new( doc, string.to_s )
  end
end
Comments