user647345
user647345

Reputation: 143

How do I select IDs using xpath in Nokogiri?

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

Answers (2)

the Tin Man
the Tin Man

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

Kobi
Kobi

Reputation: 138147

Try this xpath expression:

//span[starts-with(@id, 'startsWith_')]

Upvotes: 0

Related Questions