用R生成XML

时间:2016-02-09 22:02:31

标签: xml r

我正在使用以下代码生成带有R的XML文件。

# R 
prefix.xml <- "<reports>
  <report type='standard'>
    <data> xxx </data>
    <data> xxx </data>
    <data> xxx </data>
  </reports>"

# dummy data.frame
df <- data.frame("xxx","yyy")

# buid XML Tree
xml <- xmlTree()
xml$addTag("report", close=FALSE, attrs=c(type="enhanced"))
xml$addTag("pages", close=FALSE)
for (i in 1:nrow(df)) {
  xml$addTag("page", close=FALSE)
  for (j in names(df)) {
    xml$addTag(j, df[i, j])
  }
  xml$closeTag()
}
xml$closeTag()
xml$closeTag()

# view XML generated
cat(saveXML(xml, prefix = prefix.xml))

# <reports>
#   <report type='standard'>
#     <data> xxx </data>
#     <data> xxx </data>
#     <data> xxx </data>
#   </report>
# <report type="enhanced">
#   <pages>
#     <page>
#       <X.xxx.>xxx</X.xxx.>
#       <X.yyy.>yyy</X.yyy.>
#     </page>
#   </pages>
# </report>

这会生成一些非常接近我正在寻找的XML。但是,因为我正在定义一个复杂的前缀,所以我要留下开放的XML标签。如果你看一下这个例子,我很容易看到我需要关闭“reports”标签。如何在R中将此结束XML标记附加到此xml对象?

1 个答案:

答案 0 :(得分:3)

使用XML包,请考虑使用newXMLNode()

prefix.xml添加节点
library(XML)

# XML STRING 
prefix.xml <- "<reports>
                  <report type='standard'>
                    <data> xxx </data>
                    <data> xxx </data>
                    <data> xxx </data>
                  </report>     
               </reports>"

# DUMMY DATA FRAME
df <- data.frame("xxx","yyy")

# BUILD XML TREE
doc = xmlTreeParse(prefix.xml, useInternalNodes = T)     # PARSE STRING
root = xmlRoot(doc)                                      # FIND ROOT

reportNode = newXMLNode("report", parent=root)           # ADD TO ROOT
xmlAttrs(reportNode) = c(type = "enhanced")              # ADD ATTRIBUTE
pagesNode = newXMLNode("pages", parent=reportNode)       # ADD TO REPORT

for (i in 1:nrow(df)){
  pageNode = newXMLNode("page", parent=pagesNode)        # ADD PAGE FOR EACH RECORD
  for (j in 1:nrow(df)){
    newXMLNode("X.xxx.", df$X.xxx.[i], parent=pageNode)  # ADD COL/ROW VALUE
    newXMLNode("X.yyy.", df$X.yyy.[i], parent=pageNode)  # ADD COL/ROW VALUE
  }  
}

# VIEW XML
print(doc)

# SAVE XML TO FILE
saveXML(doc, file="OutputFile.xml")

#<?xml version="1.0"?>
#<reports>
#  <report type="standard">
#    <data> xxx </data>
#    <data> xxx </data>
#    <data> xxx </data>
#  </report>
#  <report type="enhanced">
#    <pages>
#      <page>
#        <X.xxx.>xxx</X.xxx.>
#        <X.yyy.>yyy</X.yyy.>
#      </page>
#    </pages>
#  </report>
#</reports>