Convert STR_CONST
text()
values into R strings. This is useful to account for arbitrary
character literals, e.g. R"------[hello]------"
, which is parsed in R as "hello"
.
It is quite cumbersome to write XPaths allowing for strings like this, so whenever your
linter logic requires testing a STR_CONST
node's value, use this function.
NB: this is also properly vectorized on s
, and accepts a variety of inputs. Empty inputs
will become NA
outputs, which helps ensure that length(get_r_string(s)) == length(s)
.
Arguments
- s
An input string or strings. If
s
is anxml_node
orxml_nodeset
andxpath
isNULL
, extract its string value withxml2::xml_text()
. Ifs
is anxml_node
orxml_nodeset
andxpath
is specified, it is extracted withxml2::xml_find_chr()
.- xpath
An XPath, passed on to
xml2::xml_find_chr()
after wrapping withstring()
.
Examples
tmp <- tempfile()
writeLines("c('a', 'b')", tmp)
expr_as_xml <- get_source_expressions(tmp)$expressions[[1L]]$xml_parsed_content
writeLines(as.character(expr_as_xml))
#>
#>
#>
#>
#> c
#>
#> (
#>
#> 'a'
#>
#> ,
#>
#> 'b'
#>
#> )
#>
#>
#>
get_r_string(expr_as_xml, "expr[2]")
#> [1] "a"
get_r_string(expr_as_xml, "expr[3]")
#> [1] "b"
unlink(tmp)
# more importantly, extract raw strings correctly
tmp_raw <- tempfile()
writeLines("c(R'(a\\b)', R'--[a\\\"\'\"\\b]--')", tmp_raw)
expr_as_xml_raw <- get_source_expressions(tmp_raw)$expressions[[1L]]$xml_parsed_content
writeLines(as.character(expr_as_xml_raw))
#>
#>
#>
#>
#> c
#>
#> (
#>
#> R'(a\b)'
#>
#> ,
#>
#> R'--[a\"'"\b]--'
#>
#> )
#>
#>
#>
get_r_string(expr_as_xml_raw, "expr[2]")
#> [1] "a\\b"
get_r_string(expr_as_xml_raw, "expr[3]")
#> [1] "a\\\"'\"\\b"
unlink(tmp_raw)