Search code examples
rxmlrvestxml2

How to check whether an XML node set is empty in R?


I'm writing a function that iterates over XML nodes in R; for this I've been looking for a verb that affirms or denies the presence of an empty XML-nodeset (something like isEmptyNodeSet).

In other words, a function that returns TRUE if a case like the following occurs:

library(magrittr)
library(rvest)
#> Loading required package: xml2
library(xml2)
"https://www.admin.ch/ch/d/gg/pc/ind2010.html" %>%
  read_html() %>%
  html_nodes("a.adminCHlink, div#spalteContentPlus h2 ~ ul") %>%
  .[[1]] %>%
  html_nodes("strong")
#> {xml_nodeset (0)}

Created on 2019-01-12 by the reprex package (v0.2.1)

Thanks so much in advance (and sorry if the answer is obvious, I'm an XML-rookie)!


Solution

  • Either use is_empty <- function(x) if(length(x) == 0) TRUE else FALSE (thanks @Chase).

    Or use rlang::is_empty() or purrr::is_empty() respectively, which does exactly the same.

    The code then becomes:

    library(magrittr)
    library(rvest)
    #> Loading required package: xml2
    library(xml2)
    "https://www.admin.ch/ch/d/gg/pc/ind2010.html" %>%
      read_html() %>%
      html_nodes("a.adminCHlink, div#spalteContentPlus h2 ~ ul") %>%
      .[[1]] %>%
      html_nodes("strong") %>%
        rlang::is_empty()
    #> [1] TRUE