Method: Nokogiri::XML::Searchable#search

Defined in:
lib/nokogiri/xml/searchable.rb

#search(*args) ⇒ Object Also known as: /

call-seq:

search(*paths, [namespace-bindings, xpath-variable-bindings, custom-handler-class])

Search this object for paths. paths must be one or more XPath or CSS queries:

node.search("div.employee", ".//title")

A hash of namespace bindings may be appended:

node.search('.//bike:tire', {'bike' => 'http://schwinn.com/'})
node.search('bike|tire', {'bike' => 'http://schwinn.com/'})

For XPath queries, a hash of variable bindings may also be appended to the namespace bindings. For example:

node.search('.//address[@domestic=$value]', nil, {:value => 'Yes'})

💡 Custom XPath functions and CSS pseudo-selectors may also be defined. To define custom functions create a class and implement the function you want to define, which will be in the ‘nokogiri` namespace in XPath queries.

The first argument to the method will be the current matching NodeSet. Any other arguments are ones that you pass in. Note that this class may appear anywhere in the argument list. For example:

handler = Class.new {
  def regex node_set, regex
    node_set.find_all { |node| node['some_attribute'] =~ /#{regex}/ }
  end
}.new
node.search('.//title[nokogiri:regex(., "\w+")]', 'div.employee:regex("[0-9]+")', handler)

See Searchable#xpath and Searchable#css for further usage help.



54
55
56
57
58
59
60
61
62
# File 'lib/nokogiri/xml/searchable.rb', line 54

def search(*args)
  paths, handler, ns, binds = extract_params(args)

  xpaths = paths.map(&:to_s).map do |path|
    LOOKS_LIKE_XPATH.match?(path) ? path : xpath_query_from_css_rule(path, ns)
  end.flatten.uniq

  xpath(*(xpaths + [ns, handler, binds].compact))
end