Method: Nokogiri::XML::Searchable#xpath

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

#xpath(*args) ⇒ Object

call-seq:

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

Search this node for XPath paths. paths must be one or more XPath queries.

node.xpath('.//title')

A hash of namespace bindings may be appended. For example:

node.xpath('.//foo:name', {'foo' => 'http://example.org/'})
node.xpath('.//xmlns:name', node.root.namespaces)

A hash of variable bindings may also be appended to the namespace bindings. For example:

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

💡 Custom XPath functions 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.

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.xpath('.//title[nokogiri:regex(., "\w+")]', handler)


179
180
181
182
183
# File 'lib/nokogiri/xml/searchable.rb', line 179

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

  xpath_internal(self, paths, handler, ns, binds)
end