Ruby – A better way to remove blank lines after Nokogiri Node removal


Perhaps this is nitpicky, but I have to ask.

I'm using Nokogiri to parse XML, remove certain tags, and write over the original file with the results. Using .remove leaves blank lines in the XML. I'm currently using a regex to get rid of the blank lines. Is there some built-in Nokogiri method I should be using?

Here's what I have:

require 'Nokogiri'
io_path = "/path/to/metadata.xml"
io =
document = Nokogiri::XML(io)
document.xpath('//artwork_files', '//tracks', '//previews').remove

# write to file and remove blank lines with a regular expression, 'w') do |x|
  x << document.to_s.gsub(/\n\s+\n/, "\n")

Best Solution

There is not built-in methods, but we can add one

class Nokogiri::XML::Document
  def remove_empty_lines!
    self.xpath("//text()").each { |text| text.content = text.content.gsub(/\n(\s*\n)+/,"\n") }; self
Related Question