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
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.