我编写了一个函数来将(大型)异构 XML 文件拆分为数据帧,其中拆分是通过 xpath 表达式完成的。我所说的异质是指感兴趣的项目属于一组不同的“列”结构。但是,对于大型ish XML 文件,比如 50K 项和 5 种类型,代码似乎比我预期的更“缓慢”。
那么问题是:是否存在我错过的执行此操作的现有功能,如果没有,是否有明显的方法可以提高下面代码的速度?
这是我正在考虑的那种 XML 结构的最小示例:
xmldoc <- xml2::read_xml(
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<resp>
<respMeta>
<status>200</status>
<!-- ... -->
</respMeta>
<content>
<list>
<item>
<Type>Type1</Type>
<ColA>Foo</ColA>
<ColB>Bar</ColB>
</item>
<item>
<Type>Type2</Type>
<ColC>Baz</ColC>
</item>
<item>
<Type>Type3</Type>
<ColA>Lorem</ColA>
<ColB>Ipsum</ColB>
<ColC>Dolor</ColC>
</item>
</list>
<!-- ... many many more entries here -->
</content>
</resp>')
目标是将其转换为N个数据帧,其中N是其中唯一值的数量//item/Type
(在解析时未知)。
这是我的实现:
#' Split XML Document into Dataframes by Xpath Expression
#'
#' @param xml An (xml2) xml document object.
#'
#' @param xpath the path to the values to split by. \code{xml_text} is used
#' to get the value.
#'
#' @importFrom xml2 xml_text xml_find_all xml_find_first xml_children xml_name
#' @importFrom stats setNames
#' @importFrom dplyr bind_cols
#' @importFrom magrittr %>%
#'
#' @return list of data frames (tbl_df)
#'
#' @export
xml_to_dfs <- function(xml, xpath)
{
u <- xml_find_all(xml, xpath) %>% xml_text %>% unique %>% sort
select <- paste0(xpath, "[. ='", u, "']/..") %>% setNames(u)
paths <-
lapply(select, . %>% xml_find_first(x = xml) %>% xml_children %>% xml_name)
queries <- Map(paste, select, paths, MoreArgs = list(sep = "/"))
columns <-
lapply(queries, . %>% lapply(. %>% xml_find_all(x = xml) %>% xml_text))
Map(setNames, columns, paths) %>% lapply(bind_cols)
}
最小示例的结果(每帧只有一行)是:
xml_to_dfs(xmldoc, "//item/Type")
$Type1
# A tibble: 1 × 3
Type ColA ColB
<chr> <chr> <chr>
1 Type1 Foo Bar
$Type2
# A tibble: 1 × 2
Type ColC
<chr> <chr>
1 Type2 Baz
$Type3
# A tibble: 1 × 4
Type ColA ColB ColC
<chr> <chr> <chr> <chr>
1 Type3 Lorem Ipsum Dolor