我正在使用该xml2
包将一个巨大的XML文件读入内存,该命令失败并出现以下错误:
错误:字符0x0超出允许范围[9]
我的代码如下所示:
library(xml2)
doc <- read_xml('~/Downloads/FBrf.xml')
Run Code Online (Sandbox Code Playgroud)
数据可以在ftp://ftp.flybase.net/releases/FB2015_05/reporting-xml/FBrf.xml.gz(大约140MB)下载,解压后大约1.8GB.
有没有人建议如何找出哪些字符有问题或如何在阅读之前清理文件.
编辑
好的,因为文件很大,我搜索了堆栈溢出的其他解决方案,并试图实现他在这里介绍的Martin Morgan的解决方案在巨大的XML文件中组合值
所以我到目前为止所做的是以下几行代码
library(XML)
branchFunction <- function(progress=10) {
res <- new.env(parent=emptyenv()) # for results
it <- 0L # iterator -- nodes visited
list(publication=function(elt) {
## handle 'publication' nodes
if (getNodeSet(elt, "not(/publication/feature/id)"))
## early exit -- no feature id
return(NULL)
it <<- it + 1L
if (it %% progress == 0L)
message(it)
publication <- getNodeSet(elt, "string(/publication/id/text())") # 'key'
res[[publication]] <-
list(miniref=getNodeSet(elt,
"normalize-space(/publication/miniref/text())"),
features= xpathSApply(elt, "//feature/id/text()", xmlValue))
}, getres = function() {
## retrieve the 'res' environment when done
res
}, get=function() {
## retrieve 'res' environment as data.frame
publication <- ls(res)
miniref <- unlist(eapply(res, "[[", "miniref"), use.names=FALSE)
feature <- eapply(res, "[[", "features")
len <- sapply(feature, length)
data.frame(publication=rep(publication, len),
feature=unlist(feature, use.names=FALSE),
miniref=rep(miniref, len))
})
}
branches <- branchFunction()
xmlEventParse("~/Downloads/jnk.xml", handlers=NULL, branches=branches)
# xmlEventParse("~/Downloads/FBrf.xml", handlers=NULL, branches=branches)
branches$get()
Run Code Online (Sandbox Code Playgroud)
我将xml文件上传到我的服务器http://download.dejung.net/jnk.xml
该文件只有几kb,但问题是结果.第二个发布条目的id为FBrf0162243,而miniref为Schwartz et al., 2003, Mol. Cell. Biol. 23(19): 6876--6886
.
我上面发布的代码的结果报告了相应miniref的错误发布ID.功能ID是正确的....
FBrf0050934 FBgn0003277 Schwartz等,2003,Mol.细胞.生物学.23(19):6876--6886
不知道为什么我的代码报告了错误的值,也许有人可以帮我解决这个问题,因为这对我来说很新.
我偶尔会遇到可能与此类似的“embedded NULL”错误消息(如果0x0
此消息中的 表示相同的NULL
问题)。我的方法是在读入文件之前尝试删除它们,因为我还没有找到忽略它们的 R 包。
如果您使用的是 Unix 或 OS X,您可以sed
通过以下方式在 R 程序中调用:
system( 'sed "s/\\0//g" ~/Downloads/dirty.xml > ~/Downloads/clean.xml' )
Run Code Online (Sandbox Code Playgroud)
如果这不起作用,您可能需要扩展这个字符“黑名单”——例如参见Unicode Regex;无效的 XML 字符
如果仍然有问题,有时我会创建一个字符白名单——删除所有不在指定字符集中的内容。
sed 's/[^A-Za-z0-9 _.,"]//g' ~/Downloads/dirty.csv > ~/Downloads/clean.csv
这是我用于 .csv 数据文件的文件(不关心</etc.>
),因此您可能希望将其扩展为以下内容[^[:ascii:]]
:
如果您使用的是 Windows,则可能必须在 R 之外才能使用此方法 - 例如,您可以使用 Cygwin 而不是system()
上面的调用。