Nokogiri to_xml without carriage returns

前端 未结 3 952
再見小時候
再見小時候 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

    Builder#to_xml by default outputs formatted (i.e. indented) XML. You can use the Nokogiri::XML::Node::SaveOptions to get an almost unformatted result.

    b = Nokogiri::XML::Builder.new do |xml|
      xml.root do
        xml.foo do
          xml.text("Value")
        end
      end
    end
    
    b.to_xml
    #=> "\n\n  Value\n\n"
    
    b.to_xml(:save_with => Nokogiri::XML::Node::SaveOptions::AS_XML)
    #=> "\nValue\n"
    

    Now you could either just get rid of the XML header (which is optional anyway) and remove the last newline

    b.to_xml(:save_with => Nokogiri::XML::Node::SaveOptions::AS_XML | Nokogiri::XML::Node::SaveOptions::NO_DECLARATION).strip
    #=> "Value"
    

    Just removing any newlines in the XML is probably a bad idea as newlines can actually be significant (e.g. in

     blocks of XHTML). If that is not the case for you (and you are really sure of that) you could just do it.

提交回复
热议问题