css_to_xpath: Translate a CSS selector to an equivalent XPath expression.

Description Usage Arguments Details Value Author(s) References Examples

View source: R/main.R

Description

This function aims to create an XPath expression equivalent to what would be matched by the given CSS selector. The reason the translation is required is because the XML and xml2 packages, being a libxml2 wrappers, can only evaluate XPath expressions.

Using this function, it is possible to search an XML tree without the prerequisite of knowing XPath.

Usage

1
2
3
css_to_xpath(selector,
             prefix = "descendant-or-self::",
             translator = "generic")

Arguments

selector

A character vector of CSS selectors.

prefix

The prefixes to apply to the resulting XPath expressions. The default or "" are most commonly used.

translator

The type of translator that will be used. Possible options are generic (the default), or html or xhtml.

Details

Each selector given to this function will be translated to an equivalent XPath expression. The resulting XPath expression can be given a prefix which determines the scope of the expression. The default prefix determines the scope to be the node itself and all descendants of the node. Most commonly the prefix is either the default or "", unless it is known what scope a particular XPath expression should have.

The translator used is usually unnecessary to specify as the default is sufficient for most cases. However, it is of use when creating expressions relating to (X)HTML pseudo elements and languages. In particular it qualifies the following pseudo selectors to apply only to relevant (X)HTML elements: :checked, :disabled, :enabled and :link.

When the translator is set to html, all elements and attributes will be converted to lower case. This restriction is removed when the translator is xhtml (or the default generic translator).

Value

A character vector of XPath expressions.

Author(s)

Simon Potter

References

CSS3 Selectors https://www.w3.org/TR/css3-selectors/, XPath https://www.w3.org/TR/xpath/.

Examples

1
2
3
4
  css_to_xpath(".testclass")
  css_to_xpath("#testid", prefix = "")
  css_to_xpath("#testid .testclass")
  css_to_xpath(":checked", translator = "html")

Example output

[1] "descendant-or-self::*[@class and contains(concat(' ', normalize-space(@class), ' '), ' testclass ')]"
[1] "*[@id = 'testid']"
[1] "descendant-or-self::*[@id = 'testid']/descendant::*[@class and contains(concat(' ', normalize-space(@class), ' '), ' testclass ')]"
[1] "descendant-or-self::*[(@selected and name(.) = 'option') or (@checked and (name(.) = 'input' or name(.) = 'command')and (@type = 'checkbox' or @type = 'radio'))]"

selectr documentation built on Jan. 11, 2020, 9:25 a.m.