Module: Nokogiri::CSS

Defined in:
lib/nokogiri/css.rb,
lib/nokogiri/css/node.rb,
lib/nokogiri/css/parser.rb,
lib/nokogiri/css/parser.rb,
lib/nokogiri/css/tokenizer.rb,
lib/nokogiri/css/syntax_error.rb,
lib/nokogiri/css/parser_extras.rb,
lib/nokogiri/css/xpath_visitor.rb

Overview

Translate a CSS selector into an XPath 1.0 query

Defined Under Namespace

Modules: XPathVisitorAlwaysUseBuiltins, XPathVisitorOptimallyUseBuiltins Classes: Node, Parser, SyntaxError, Tokenizer, XPathVisitor

Class Method Summary collapse

Class Method Details

.parse(selector) ⇒ Object

TODO: Deprecate this method ahead of 2.0 and delete it in 2.0. It is not used by Nokogiri and shouldn’t be part of the public API.



10
11
12
# File 'lib/nokogiri/css.rb', line 10

def parse(selector) # :nodoc:
  Parser.new.parse(selector)
end

.xpath_for(selector, options = {}) ⇒ Object

:call-seq:

xpath_for(selector) → String
xpath_for(selector [, prefix:] [, visitor:] [, ns:]) → String

Translate a CSS selector to the equivalent XPath query.

Parameters
  • selector (String) The CSS selector to be translated into XPath

  • prefix: (String)

    The XPath prefix for the query, see Nokogiri::XML::XPath for some options. Default is XML::XPath::GLOBAL_SEARCH_PREFIX.

  • visitor: (Nokogiri::CSS::XPathVisitor)

    The visitor class to use to transform the AST into XPath. Default is Nokogiri::CSS::XPathVisitor.new.

  • ns: (Hash<String ⇒ String>)

    The namespaces that are referenced in the query, if any. This is a hash where the keys are the namespace prefix and the values are the namespace URIs. Default is an empty Hash.

Returns

(String) The equivalent XPath query for selector

💡 Note that translated queries are cached for performance concerns.

Raises:

  • (TypeError)


42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/nokogiri/css.rb', line 42

def xpath_for(selector, options = {})
  raise TypeError, "no implicit conversion of #{selector.inspect} to String" unless selector.respond_to?(:to_str)

  selector = selector.to_str
  raise Nokogiri::CSS::SyntaxError, "empty CSS selector" if selector.empty?

  prefix = options.fetch(:prefix, Nokogiri::XML::XPath::GLOBAL_SEARCH_PREFIX)
  visitor = options.fetch(:visitor) { Nokogiri::CSS::XPathVisitor.new }
  ns = options.fetch(:ns, {})

  Parser.new(ns).xpath_for(selector, prefix, visitor)
end