How do I remove a node with Nokogiri?

RubyNokogiri

Ruby Problem Overview


How can I remove <img> tags using Nokogiri?

I have the following code but it wont work:

# str = '<img src="canadascapital.gc.ca/data/2/rec_imgs/5005_Pepsi_H1NB.gif"/…; testt<a href="#">test</a>tfbu' 

f = Nokogiri::XML.fragment(str)
f.search('//img').each do |node| 
  node.remove
end
puts f

Ruby Solutions


Solution 1 - Ruby

have a try!

f = Nokogiri::XML.fragment(str)

f.search('.//img').remove
puts f

Solution 2 - Ruby

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"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionall jazzView Question on Stackoverflow
Solution 1 - Rubyxds2000View Answer on Stackoverflow
Solution 2 - Rubythe Tin ManView Answer on Stackoverflow