删除Nokogiri节点后删除空行的更好方法

mic*_*ael 8 ruby xml nokogiri

也许这是挑剔,但我不得不问.

我正在使用Nokogiri解析XML,删除某些标签,并用结果写入原始文件..remove在XML中使用叶子空白行.我目前正在使用正则表达式来摆脱空白行.我应该使用一些内置的Nokogiri方法吗?

这就是我所拥有的:

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

# write to file and remove blank lines with a regular expression
File.open(io_path, 'w') do |x|
  x << document.to_s.gsub(/\n\s+\n/, "\n")
end
Run Code Online (Sandbox Code Playgroud)

aku*_*uhn 7

没有内置方法,但我们可以添加一个

class Nokogiri::XML::Document
  def remove_empty_lines!
    self.xpath("//text()").each { |text| text.content = text.content.gsub(/\n(\s*\n)+/,"\n") }; self
  end
end
Run Code Online (Sandbox Code Playgroud)