How do I remove a node with Nokogiri?

前端 未结 2 628
面向向阳花
面向向阳花 2020-12-14 05:14

How can I remove tags using Nokogiri?

I have the following code but it wont work:

# str = \'

        
相关标签:
2条回答
  • 2020-12-14 06:05

    have a try!

    f = Nokogiri::XML.fragment(str)
    
    f.search('.//img').remove
    puts f
    
    0 讨论(0)
  • 2020-12-14 06:21

    I prefer CSS over XPath, as it's usually much more readable. Switching to CSS:

    require 'nokogiri'
    
    doc = Nokogiri::HTML('<html><body><img src="foo"><img src="bar"></body></html>')
    

    After parsing the document looks like:

    doc.to_html
    # => "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/REC-html40/loose.dtd\">\n<html><body>\n<img src=\"foo\"><img src=\"bar\">\n</body></html>\n"
    

    Removing the <img> tags:

    doc.search('img').each do |src|
      src.remove
    end
    

    Results in:

    doc.to_html
    # => "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/REC-html40/loose.dtd\">\n<html><body></body></html>\n"
    
    0 讨论(0)
提交回复
热议问题