我正在尝试将此xml_file(以及许多其他类似文件)转换为 R 中的 data.frame。期望的结果:具有以下内容的 data.frame(或 tibble、data.table 等):
- 每行
Deputado
(这是 的主要标签/级别xml_file
,其中有 4 个) - 每个 Deputado 中的所有变量都应该是列。
- 可以忽略具有多个值的嵌套类别(例如
comissao
、等)。cargoComissoes
在下面的代码中,我尝试密切关注github/.../xmltools 的自述文件中的示例 2,但出现错误:
...
+ dplyr::mutate_all(empty_as_na)
Error: Argument 4 must be length 4, not 39
任何解决此问题的帮助(或完整示例的不同策略)将不胜感激。
代码(具有可重现的错误)是:
file <- "https://www.camara.leg.br/SitCamaraWS/Deputados.asmx/ObterDetalhesDeputado?ideCadastro=141428&numLegislatura="
doc <- file %>%
xml2::read_xml()
nodeset <- doc %>%
xml2::xml_children()
length(nodeset) # lots of nodes!
nodeset[1] %>% # lets look at ONE node's tree
xml_view_tree()
# lets assume that most nodes share the same structure
terminal_paths <- nodeset[1] %>%
xml_get_paths(only_terminal_parent = TRUE)
terminal_xpaths <- terminal_paths %>% ## collapse xpaths to unique only
unlist() %>%
unique()
# xml_to_df (XML package based)
## note that we use file, not doc, hence is_xml = FALSE
# df1 <- lapply(xpaths, xml_to_df, file = file, is_xml = FALSE, dig = FALSE) %>%
# dplyr::bind_cols()
# df1
# xml_dig_df (xml2 package based)
## faster!
empty_as_na <- function(x){
if("factor" %in% class(x)) x <- as.character(x) ## since ifelse wont work with factors
if(class(x) == "character") ifelse(as.character(x)!="", x, NA) else x
}
terminal_nodesets <- lapply(terminal_xpaths, xml2::xml_find_all, x = doc) # use xml docs, not nodesets! I think this is because it searches the 'root'.
df2 <- terminal_nodesets %>%
purrr::map(xml_dig_df) %>%
purrr::map(dplyr::bind_rows) %>%
dplyr::bind_cols() %>%
dplyr::mutate_all(empty_as_na)