1

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

  • Not sure about the second option. But the first option would remove all white space what would certainly break documents. Imagine you have this very basic XML document __ and remove all white space. – spickermann Nov 26 '20 at 16:28
  • your full-file string can be accessed with `xml_file.to_xml` from there you can replace/delete what you want. But I would warn you that the string representation is generated automatically and should not be played around too much. Lastly, your XML as two `root` node, watch out ;) – Pierre-Louis Lacorte Nov 26 '20 at 16:31
  • thanks. It actually now deletes all the whitespaces, but I do want some whitespaces, like between "first_node id=...". Any idea about this? – Andrea Vettorino Nov 26 '20 at 17:00
  • I have done: xml_file.to_xml.split.join(" ").gsub("> <","><") and it seems to work. Thanks – Andrea Vettorino Nov 26 '20 at 17:25

1 Answers1

3

Following should give you what you are looking for

string.gsub(/\\n/, '').gsub(/>\s*/, ">").gsub(/\s*</, "<")
Gowtham
  • 624
  • 5
  • 9