2016-02-05 79 views
3

我有一個簡單的data.frame有兩個變量,title和base64。我需要將這個data.frame轉換成XML格式。例如繼承人什麼我的數據看起來像..如何將data.frame轉換爲帶R的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) 結構(表(頁= C( 「壹」, 「第二頁」),基數64 = C(「甚長字符串這是一個base64字符「, 」非常長的字符串thats一個base64字符「)),.Names = c(」page「, 」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> 

我一直在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 

回答

6

至於this answer,我會做

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

當我運行這段代碼我只得到 「<?XML版本=」 1.0 「?>」 ??? – Nodedeveloper101

+0

奇怪。我的'packageVersion(「XML」)'是'3.98.1.3' - 在這裏工作。 – lukeA

+0

我重新啓動R,它的工作,謝謝 – Nodedeveloper101