如何使用Nokogiri Builder添加评论

zet*_*ish 5 ruby xml nokogiri

如何<!-- blahblah -->使用Nokogiri的Builder向XML 添加注释?

我希望有类似的东西:

<root>
  <!--blahblah-->
  <child/>
</root>
Run Code Online (Sandbox Code Playgroud)

我尝试这样的事情:

Nokogiri::XML::Builder.new do |xml|
  xml.root {
    xml.comment('blahblah')
    xml.child
  }
end
Run Code Online (Sandbox Code Playgroud)

但这给了我:

<root>
  <comment>blahblah</comment>
  <child/>
</root>
Run Code Online (Sandbox Code Playgroud)

Phr*_*ogz 4

您可以使用以下方法解决当前版本中不存在的已记录的未来功能的错误Builder#<<

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>
Run Code Online (Sandbox Code Playgroud)

或者,您可以在您自己的 future 方法版本中进行 Monkeypatch:

class Nokogiri::XML::Builder
  def comment(string)
    insert Nokogiri::XML::Comment.new( doc, string.to_s )
  end
end
Run Code Online (Sandbox Code Playgroud)