2

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

4
  • 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 <?xml version="1.0" encoding="UTF-8"?> and remove all white space. Commented Nov 26, 2020 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 ;) Commented Nov 26, 2020 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? Commented Nov 26, 2020 at 17:00
  • 1
    I have done: xml_file.to_xml.split.join(" ").gsub("> <","><") and it seems to work. Thanks Commented Nov 26, 2020 at 17:25

1 Answer 1

3

Following should give you what you are looking for

string.gsub(/\\n/, '').gsub(/>\s*/, ">").gsub(/\s*</, "<")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.