首页 > 解决方案 > 在循环中读取 R 中的 XML 文件崩溃

问题描述

我有一个循环遍历 xml 文件列表并处理它们的代码。当我为单个 xml 执行代码时,结果是预期的。但是当我开始循环时,不同的文件中会出现意外错误。错误的文件在每次迭代中都会更改,因此没有模式可以找到错误。

前任。单个文件:

p_xml <- function(file)
{
   tmp<-tryCatch(
  {
    (read_xml(path_XML))
  },error=function(e)
  {
    return(NA)
   })

 if(is.na(tmp))
   {
    file <- read_xml(path_XML, encoding = "ISO-8859-1")
  }else{
   file <- tmp
 }
 id <- as.numeric(xml_attr(file, "id"))
 year_id <- as.numeric(xml_attr(file, "machine_year"))

....

return(data)

}

此代码以正确的方式返回 data.table。但是如果我在一个循环中执行这个函数:

global_dt<-data.table()
for(j in 1:length(file_names))
  {
    current_file <- file_names[j]
    f <- p_xml(file.path(current_dir,current_file))
    global_dt<-rbind(global_dt,f)
  }

我收到这样的错误:

  • doc_parse_file 中的错误(con,encoding = encoding,as_html = as_html,options = options):无法解析 /path/file.xml *

事实是,如果我随后使用失败的文件执行单个代码,它会返回我所期望的。我使用 xml2 库来读取文件

标签: rxmlencodingxml2

解决方案


试试这个工作流程

library(data.table)
#store the result of each run of the function into a list
l <- lapply( list_files, p_xml )
#rowbind the list together into one data.table
global_dt <- data.table::rbindlist( l ) 

推荐阅读