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


i have simple data.frame 2 variables, title , base64. need transform data.frame xml format. example heres data looks like..

str(df)      'data.frame':  2 obs. of  2 variables:      $ title  : chr  "page one" "page two"      $ base64: chr  "very long string thats base64 character" "very long string thats base64 character" 

dput(df) structure(list(page = c("page one", "page two"), base64 = c("very long string thats base64 character", "very long string thats base64 character")), .names = c("page", "base64"), row.names = 1:2, class = "data.frame")

i need output xml file has format looks 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 xml package in r , found function seems should work, cannot figure out. appreciated.

library(xml) converttoxml <- function(df,name) {   xml <- xmltree("report")   xml$addnode(name, close=false)   (i in 1:nrow(df)) {     xml$addnode("page", close=false)     (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 looks 

with regards this answer, i'd do

data<- structure(list(page = c("page one", "page two"), base64 = c("very long string thats base64 character", "very long string thats 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) (i in 1:nrow(data)) {     xml$addtag("page", close=false)     (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 base64 character</page> #     </page> #     <page> #       <title>page two</title> #       <page>very long string thats base64 character</page> #     </page> #   </pages> # </report> 

Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -