【问题标题】:Read XML files in R crashes in loops在循环中读取 R 中的 XML 文件崩溃
【发布时间】:2019-03-25 11:41:54
【问题描述】:

我有一个循环遍历 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 库来读取文件

【问题讨论】:

    标签: r xml encoding xml2


    【解决方案1】:

    试试这个工作流程

    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 ) 
    

    【讨论】:

    • 感谢您的回答。错误仍然存​​在于不同的文件中。错误是相同的,但我可以更新 3 个警告:此外:警告消息:1:在 doc_parse_file(con,encoding = encoding,as_html = as_html,options = options):打开文件过多 [1518] 2:在doc_parse_file(con, encoding = encoding, as_html = as_html, options = options) : 打开的文件太多 [1518] 3: 在 doc_parse_file(con, encoding = encoding, as_html = as_html, options = options) 中:
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-16
    • 2011-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-09
    • 1970-01-01
    相关资源
    最近更新 更多