How to add a comment in Nokogiri Builder

How to add <!-- blahblah --> comment to XML using Nokogiri Builder?

I want to have something like:

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

I am trying something like this:

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

But it gives me:

 <root> <comment>blahblah</comment> <child/> </root> 
+4
source share
3 answers

You can work around this error with a documented future function missing in the current version 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 defuse your own version of a future method:

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

By the way, this may be obvious, but since xml.comment creates an XML comment now, if you need to create a <comment> element, you should use

  xml << "<comment>#{comment}</comment>" 

It happened to me. Thank you for hinting at the <Method.

0
source

Since V1.6.8 is supported by comment -option, you do not need to work with << .

If you need a comment tag, you can use comment_ (with an underscore at the end).

Example:

 builder = Nokogiri::XML::Builder.new do |xml| xml.root { xml.comment 'My comment' xml.comment_ 'My comment-tag' } end puts builder.to_xml 

Result:

 <?xml version="1.0"?> <root> <!--My comment--> <comment>My comment-tag</comment> </root> 
0
source

Source: https://habr.com/ru/post/1398511/


All Articles