如何使用R将data.frame转换为xml文件?
我有一个简单的data.frame,有两个变量,title和base64。我需要将这个data.frame转换成XML格式。例如,以下是我的数据如何使用R将data.frame转换为xml文件?,xml,r,Xml,R,我有一个简单的data.frame,有两个变量,title和base64。我需要将这个data.frame转换成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
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(“页面”,
“base64”),row.names=1:2,class=“data.frame”)
我需要输出一个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>
第一页
***长base64字符串***
第二页
***长base64字符串***
我一直在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
库(XML)
关于,我愿意
dataStrange。我的packageVersion(“XML”)
是“3.98.1.3”-在这里工作。使用干净的R会话重新启动?我如何将该输出导出到XML文件@lukeA,nvm'cat(saveXML(xml,data.xml)),例如saveXML(xml,file=tf
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>