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. 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:

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

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


48
49
50
51
52
53
54
55
56
# File 'lib/nokogiri/xml/searchable.rb', line 48

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

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

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