简体   繁体   中英

How to generate a xml from a data.frame R

I would like to generate an xml file from a dataframe in R. Here is an example :

data.frame

x y z
1 2 'bla'
3 4 'blou'
5 7 'bli'

Xml result :

  <xml>
    <tuple x="1" y="2" z="bla" \>
    <tuple x="3" y="4" z="blou" \>
    <tuple x="5" y="7" z="bli" \>
 </xml>

Maybe something like this helps:

d <- data.frame(x=1:3, y=3:5, z=c("foo", "bar", "baz"))
cat(paste("<xml>", paste('<tuple x="', d$x, '" y="', d$y, '" z="', d$z, '" \\>"', sep="", collapse="\n"), "</xml>", sep="\n"), "\n")
## <xml>
## <tuple x="1" y="3" z="foo" \>"
## <tuple x="2" y="4" z="bar" \>"
## <tuple x="3" y="5" z="baz" \>"
## </xml> 

Here is what you're looking for using the XML package

dat <- data.frame(x=c(1,3,5), y=c(2,4,7), z=c("bla", "blou", "bli"))
dat$z <- as.character(dat$z)
library(XML)
top <- newXMLNode("xml")
newXMLNode("tuple", attrs = dat[1,], parent = top)
newXMLNode("tuple", attrs = dat[2,], parent = top)
newXMLNode("tuple", attrs = dat[3,], parent = top)
top

Gives the output:

<xml>
 <tuple x="1" y="2" z="bla"/>
 <tuple x="3" y="4" z="blou"/>
 <tuple x="5" y="7" z="bli"/>
</xml> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM