代码之家  ›  专栏  ›  技术社区  ›  michaelmichael

移除nokogiri节点后移除空白行的更好方法

  •  8
  • michaelmichael  · 技术社区  · 15 年前

    也许这是吹毛求疵,但我不得不问。

    我使用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
    
    3 回复  |  直到 8 年前
        1
  •  7
  •   akuhn    15 年前

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

    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
    
        2
  •  2
  •   digitalronin    8 年前

    这为我删除了空白行;

    doc.xpath('//text()').find_all {|t| t.to_s.strip == ''}.map(&:remove)
    
        3
  •  1
  •   Mike Ciul    10 年前

    在每个文本节点上进行替换对我也不起作用。问题是,删除节点后,刚成为相邻节点的文本节点不会合并。循环文本节点时,每个节点只有一条换行符,但现在一行中有几个换行符。

    我发现一个相当混乱的解决方案是重新编写文档:

    xml = Nokogiri::XML.parse xml.to_xml
    

    现在,相邻的文本节点将被合并,您可以对它们执行regex。

    但这似乎是一个更好的选择:

    https://github.com/tobym/nokogiri-pretty