如何使用R将数据框转换为XML文件?

7

我有一个简单的数据框,其中包含两个变量:标题和base64。我需要将此数据框转换为XML格式。例如,这是我的数据长什么样子...

str(df)
     'data.frame':  2 obs. of  2 variables:
     $ title  : chr  "Page One" "Page Two"
     $ base64: chr  "Very Long String thats a base64 character" "Very Long String thats a base64 character"

dput(df) 结构(list(page = c("第一页", "第二页"), base64 = c("非常长的字符串,是一个base64字符", "非常长的字符串,是一个base64字符")), .Names = c("page", "base64"), 行名 = 1:2, 类别 = "数据框")

我需要输出一个XML文件,其格式如下...

<report type="enchanced">
    <pages>
        <page>
            <title>Page One</title>
            <page> *** long base64 string *** </page>
        </page>
        <page>
            <title>Page Two</title>
            <page> *** long base64 string *** </page>
        </page>
    </pages>
</report>

我一直在使用R中的XML包进行实验,甚至找到了这个看起来应该可行的函数,但我无法理解它。非常感谢您的帮助。

library(XML)
convertToXML <- function(df,name) {
  xml <- xmlTree("report")
  xml$addNode(name, close=FALSE)
  for (i in 1:nrow(df)) {
    xml$addNode("page", close=FALSE)
    for (j in names(df)) {
      xml$addNode(j, df[i, j])
    }
    xml$closeTag()
  }
  xml$closeTag()
  return(xml)
}

 tr = convertToXML(df,"pages") 
 cat(saveXML(tr$page())) ## suppose to looks good
1个回答

11

关于这个答案,我会做……

data<- structure(list(page = c("Page One", "Page Two"), base64 = c("Very Long String thats a base64 character", "Very Long String thats a base64 character")), .Names = c("page", "base64"), row.names = 1:2, class = "data.frame")
names(data) <- c("title", "page")

library(XML)
xml <- xmlTree()
# names(xml)
xml$addTag("report", close=FALSE, attrs=c(type="enhanced"))
xml$addTag("pages", close=FALSE)
for (i in 1:nrow(data)) {
    xml$addTag("page", close=FALSE)
    for (j in names(data)) {
        xml$addTag(j, data[i, j])
    }
    xml$closeTag()
}
xml$closeTag()
xml$closeTag()
cat(saveXML(xml))
# <?xml version="1.0"?>
# 
# <report type="enhanced">
#   <pages>
#     <page>
#       <title>Page One</title>
#       <page>Very Long String thats a base64 character</page>
#     </page>
#     <page>
#       <title>Page Two</title>
#       <page>Very Long String thats a base64 character</page>
#     </page>
#   </pages>
# </report>

奇怪。我的 packageVersion("XML") 是 '3.98.1.3' - 在这里可以工作。 - lukeA
1
重新启动一个干净的 R 会话? - lukeA
我该如何将输出导出为XML文件?@lukeA,nvm 'cat(saveXML(xml, "data.xml")' - Nodedeveloper101
1
例如 saveXML(xml, file = tf <- tempfile(fileext = ".xml")) 或者 cat(as(xml, "character"), file=tf <- tempfile(fileext = ".xml"), sep="\n") - lukeA

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接