【问题标题】:R XML - cannot remove internal C nodes from memoryR XML - 无法从内存中删除内部 C 节点
【发布时间】:2016-10-20 23:25:09
【问题描述】:

我必须解析约 2000 个 xml 文档,从每个文档中提取某些节点,将它们添加到单个文档中,然后保存。我正在使用内部 C 节点,以便可以使用 XPath。问题是,当我遍历文档时,我无法从内存中删除内部 C 对象,最终得到 >4GB 的已用内存。我知道问题不在于加载的树(我运行循环时只加载和删除每个文档的哈希树),而在于过滤的节点或根节点。

这是我正在使用的代码。我错过了什么,以便在每次迭代结束时清除内存?

xmlDoc <- xmlHashTree()
rootNode <- newXMLNode("root")

for (i in seq_along(all.docs)){

  # Read in the doc, filter out nodes, remove temp doc
  temp.xml <- xmlParse(all.docs[i])
  filteredNodes <- newXMLNode(all.docs[i],
                   xpathApply(temp.xml,"//my.node[@my.attr='my.value'"))
  free(temp.xml)
  rm(temp.xml)

  # Add filtered nodes to root node and get rid of them.
  addChildren(rootNode, filteredNodes)
  removeNodes(filteredNodes, free = TRUE)
  rm(filteredNodes)

}
# Add root node to doc and save that new log.
xmlDoc <- addChildren(root)
saveXML(xmlDoc, "MergedDocs.xml") 

感谢您的帮助

【问题讨论】:

  • 您已经在使用free(),因此您可能想尝试在某处添加gc() 或切换到xml2 包(不确定它是否支持您正在做的一切,但它对某些事情有更好的内存管理)。
  • 谢谢,但它没有这样做。即使在循环外运行gc() 也不会清除内存。
  • IIRC,XML 包存在无法避免的已知内存泄漏。您可以尝试查看 xml2

标签: c r xml memory-management


【解决方案1】:

所以我发现没有办法在没有内存泄漏和大量处理时间的情况下使用“XML”。 幸运的是,“xml2”现在可以处理创建文档和节点。为了完整起见,这里是使用“xml2”的解决方案。如果有人知道使用“XML”的方法,请加入。

xmlDoc <- xml_new_document() %>% xml_add_child("root")

for (i in seq_along(all.docs)){
 # Read in the log.
 rawXML <- read_xml(all.docs[i])

 # Filter relevant nodes and cast them to a list of children.
 tempNodes   <- xml_find_all(rawXML, "//my.node[@my.attr='my.value'")
 theChildren <- xml_children(tempNodes)

 # Get rid of the temp doc.
 rm(rawXML)

 # Add the filtered nodes to the log under a node named after the file name
 xmlDoc %>%
  xml_add_child(all.docs[i]  %>%
  xml_add_child(theChildren[[1]]) %>%
  invisible()

 # Remove the temp objects
 rm(tempNodes); rm(theChildren)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-31
    • 2016-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多