Reputation: 143
Using this code:
doc = Nokogiri::HTML(open("text.html"))
doc.xpath("//span[@id='startsWith_']").remove
I would like to select every span#id
starting with 'startsWith_'
and remove it. I tried searching, but failed.
Upvotes: 1
Views: 2136
Reputation: 160631
Here's an example:
require 'nokogiri'
html = '
<html>
<body>
<span id="doesnt_start_with">foo</span>
<span id="startsWith_bar">bar</span>
</body>
</html>'
doc = Nokogiri::HTML(html)
p doc.search('//span[starts-with(@id, "startsWith_")]').to_xml
That's how to select them.
doc.search('//span[starts-with(@id, "startsWith_")]').each do |n|
n.remove
end
That's how to remove them.
p doc.to_xml
# >> "<span id=\"startsWith_bar\">bar</span>"
# >> "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/REC-html40/loose.dtd\">\n<html><body>\n <span id=\"doesnt_start_with\">foo</span>\n \n</body></html>\n"
The page "XPath, XQuery, and XSLT Functions" has a list of the available functions.
Upvotes: 1