Nokogiri replace tag values

前端 未结 2 1189
情书的邮戳
情书的邮戳 2021-01-21 23:55

How to replace \"foo\" to \"bar\" ?

From

foo1

foo2foo4foo5

foo6

2条回答
  •  一生所求
    2021-01-22 00:33

    require 'rubygems'
    require 'nokogiri'
    
    doc = Nokogiri::HTML(DATA)
    
    doc.xpath('//text()').each {|foo|
      dummy = foo.add_previous_sibling(Nokogiri::XML::Node.new("dummy", doc))
      dummy.add_previous_sibling(Nokogiri::XML::Text.new(foo.to_s.gsub(/foo/, "bar"), doc))
      foo.remove
      dummy.remove
    }
    puts doc
    
    __END__
    

    foo1

    foo2foo4foo5

    foo6

    I would have thought foo.inner_html.gsub!(/foo/, "bar") works or maybe foo.inner_html = foo.inner_html.gsub(/foo/, "bar"), but it doesn't.
    The dummy node is to keep the new text node becoming one with the old text node.

提交回复
热议问题