Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How convert a data.frame into a xml file with R?

Tags:

r

xml

I have a simple data.frame with two variables, title and base64. I need to transform this data.frame into XML format. For example heres what my data looks like..

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) 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")

I need to output a XML file that has a format that looks like this...

<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>

I've been experimenting with the XML package in R and even found this function that seems like it should work, but I cannot figure it out. Any help is greatly appreciated.

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
like image 810
Nodedeveloper101 Avatar asked Feb 05 '16 22:02

Nodedeveloper101


1 Answers

With regards to this answer, I'd do

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>
like image 166
lukeA Avatar answered Sep 30 '22 13:09

lukeA