rubyxmlnonblank

remove whitespace from xml document using ruby


I have created an XML file with Ruby:

xml_file = Nokogiri::XML::Builder.new do |xml|
  xml.root {
    xml.first_node("id" => "12") {
        xml.second_node {
        }
    }
  }
end

The output is full of /n and white spaces, like:

</first_node id="12">\n      <Second_node>

I would like something like:

</first_node id="12"><Second_node>

I have found something like:

string.delete(' '), 

but in this case it deletes ALL whitespaces, that it is not what I want. This would be the result:

 </first_nodeid="12"><Second_node>

This is why I tried using Nokogiri. I tried something like:

doc = Nokogiri::XML(File.open("file_name.xml")) do |config|
  config.strict.noblanks
end

but I am not sure, how shall apply the .noblanks to my file? Is there another solution? Thank you


Solution

  • Following should give you what you are looking for

    string.gsub(/\\n/, '').gsub(/>\s*/, ">").gsub(/\s*</, "<")