Nokogiri to_xml without carriage returns

前端 未结 3 946
再見小時候
再見小時候 2020-12-30 02:04

I\'m currently using the Nokogiri::XML::Builder class to construct an XML document, then calling .to_xml on it. The resulting string always contains a bunch of spaces, line

3条回答
  •  既然无缘
    2020-12-30 02:13

    This is not something that Nokogiri is designed to do. The closest you can get is to serialize the root of the document with no newlines or indentation, and then add the PI yourself (if you really need it):

    require 'nokogiri'
    
    b = Nokogiri::XML::Builder.new{ |xml| xml.root{ xml.foo "Value" } }
    p b.to_xml
    #=> "\n\n  Value\n\n"
    
    p b.doc.serialize(save_with:0)
    #=> "\nValue\n"
    
    flat_root = b.doc.root.serialize(save_with:0)
    p flat_root
    #=> "Value"
    
    puts %Q{#{flat_root}}
    #=> Value
    

    Alternatively, you could simply cheat and do:

    puts b.doc.serialize(save_with:0).sub("\n","")
    #=> Value
    

    Note the usage of sub instead of gsub to only replace the first known-present newline.

提交回复
热议问题