views:

623

answers:

3

given:

require 'rubygems'
require 'nokogiri'
value = Nokogiri::HTML.parse(<<-HTML_END)
"<html>
<body>
  <p id='para-1'>A</p>
  <div class='block' id='X1'>
    <h1>Foo</h1>
    <p id='para-2'>B</p>
  </div>
  <p id='para-3'>C</p>
  <h2>Bar</h2>
  <p id='para-4'>D</p>
  <p id='para-5'>E</p>
  <div class='block' id='X2'>
    <p id='para-6'>F</p>
  </div>
</body>
</html>"
HTML_END


I want to do something like what I can do in Hpricot:

divs = value.search('//div[@id^="para-"]')

1) how to do a pattern search for elements in xpath style? 2) where would I find the documentation to help me? I didn't see this in the rdocs

+2  A: 

Use the xpath function "starts-with":

value.xpath('//p[starts-with(@id, "para-")]').each { |x| puts x['id'] }
Aaron Patterson
Wow, Aaron himself just answered it!
khelll
+1  A: 

And some docs you're seeking:

andre-r
+1  A: 

divs = value.css('div[id^="para-"]')

insane.dreamer