【问题标题】:Using R to download and read zipped xml file使用 R 下载和读取压缩的 xml 文件
【发布时间】:2014-07-29 08:07:58
【问题描述】:

根据 Dirk Eddelbuettel 的this 回答,我正在尝试从zip 存档中读取xml 文件以进行进一步处理。除了 URL 和文件名之外,对引用代码的唯一更改是我将 read.table 更改为 xmlInternalTreeParse

library(XML)
temp <- tempfile()
download.file("http://epp.eurostat.ec.europa.eu/NavTree_prod/everybody/BulkDownloadListing?sort=1&downfile=data%2Fnrg_105a.sdmx.zip",temp)
doc <- xmlInternalTreeParse(unz(temp, "nrg_105a.dsd.xml"))
fileunlink(temp)
closeAllConnections()

但是,这会返回以下错误:

Error in file.exists(file) : invalid 'file' argument

traceback()表明这是来自解析器的函数调用。所以 temp 在这种情况下似乎是一个不恰当的参考。有没有办法让它工作?

【问题讨论】:

  • xmlInternalTreeParse 的工作方式似乎与read.table 不同。根据文档,read.table 可以使用连接对象,xmlInternalTreeParse 需要文件名(作为字符)。
  • 嗯,我从来没有真正理解什么是连接。所以我可能需要使用readLines 或类似的东西将连接转换为字符向量。

标签: xml r zip


【解决方案1】:

你可以试试:

# Make a temporary file (tf) and a temporary folder (tdir)
tf <- tempfile(tmpdir = tdir <- tempdir())

## Download the zip file 
download.file("http://epp.eurostat.ec.europa.eu/NavTree_prod/everybody/BulkDownloadListing?sort=1&downfile=data%2Fnrg_105a.sdmx.zip", tf)

## Unzip it in the temp folder
xml_files <- unzip(tf, exdir = tdir)

## Parse the first file
doc <- xmlInternalTreeParse(xml_files[1])

## Delete temporary files
unlink(tdir, T, T)

【讨论】:

  • 这很好。经过仔细检查,我发现这两个代码的作用基本相同,但您的代码使用unzip而不是unz。使用前者也可以运行原始脚本。
  • 问题是xmlInternalTreeParse 需要一个文件名,而不是一个连接(unz 返回的内容)。是的,您是对的,但它会将提取的 xml 保存在您的当前目录中。
猜你喜欢
  • 2014-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-03
相关资源
最近更新 更多