You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R语言中保存独立XML文件(非Rdata格式)

问题描述

我找不到在R语言中保存XML文件的方法,不需要保存为Rdata格式,而是要保存为独立文件到指定目录。查资料只找到cat(saveXML(filename)),但它只在控制台打印内容,没法实际存到文件里。以下是我的实现代码,求帮忙:

#XML package must be installed to run this code.
library(XML)
library(xml2)

setwd("C:/Users/theodore.j.gustafson/Desktop/figuringthingsout")

createXML <- function(name, date, by){
  #variable notes: name is a string of names.
  
  for(i in 1:length(name)){
    
    entryName = c("SensorName", "Fidelity", "FieldOfRegardAngularOffsetFromMountInDegrees",
                  "FieldOfRegardAngularWidthInDegrees", "IsVertical")
    string = c(as.character(name[i]), "taco", "5", "taco2", "taco3")
    
    Bookdf1 <- as.data.frame(cbind(entryName, string))
    
    names(Bookdf1) <- c("entryName", "string")
    
    doc <- xmlTree()
    
    #Open initial XML tag.
    doc$addTag("net.onesaf.core.services.model.representation.actor.ComponentComposition", close = FALSE,
               attrs = c("xmlns:xsi" = "http://www.w3.org/2001/XMLSchema-instance", "xsi:noNamespaceSchemaLocation" = "componentComposition.xsd", refID = "1"))
    doc$addTag("name", "component/physical/sensor/mr/", as.character(name[i]), close = TRUE)
    doc$addTag("displayName", as.character(name[i]), close = TRUE)
    doc$addTag("description", close = FALSE)
    doc$addTag("net.onesaf.core.services.model.representation.HTMLString", close = FALSE, attrs = c(refID = "2"))
    doc$addTag("htmlString", as.character(name[i]), close = TRUE)
    doc$closeTag() # description
    doc$closeTag() # html string
    doc$addTag("semanticDescription", close = TRUE)
    doc$addTag("country", "US", close = TRUE)
    doc$addTag("heritage", "TRAC_WSMR", close = TRUE)
    doc$addTag("serviceBranch", "ARMY", close = TRUE)
    doc$addTag("agentClassName", "net.onesaf.core.services.model.physical.sensor.PassiveSensor", close = TRUE)
    #body req here
    doc$addTag("bodyRequirement", "NONE", close = TRUE)
    #echelon here
    doc$addTag("echelonList", "both", close = TRUE)
    #Only if needed add things to the bottom 3.
    doc$addTag("placeholders", close = TRUE)
    doc$addTag("placeholdersList", close = TRUE)
    doc$addTag("keywordList", close = TRUE)
    #enter todays date here
    doc$addTag("lastModifiedDate", date, close = TRUE)
    #enter your name here
    doc$addTag("lastModifiedBy", by, close = TRUE)
    #Open model which begins building the entity.
    doc$addTag("models", close = FALSE)
    #Open model composition.
    doc$addTag("net.onesaf.core.services.model.representation.actor.ModelComposition", close = FALSE, attrs = c(refID = "3"))
    doc$addTag("implClassName", "net.onesaf.ext.trac.models.phys.sensor.mr.AMSAATTPTASAcquisitionModel", close = TRUE)
    doc$addTag("interfaceClassName", "net.onesaf.core.services.model.physical.sensor.AbstractPassiveSensorModel", close = TRUE)
    #open data, begins to populate sensor information
    doc$addTag("data", close = FALSE)
    #open and close while populating data with each individual entry name and string from above.
    h = 3
    for(j in 1:nrow(Bookdf1)){
      
      doc$addTag("net.onesaf.core.services.model.representation.actor.ModelDataEntry", close = FALSE, attrs = c(refID = as.character(j+3)))
      for(k in names(Bookdf1)){
        
        doc$addTag(k, Bookdf1[j,k])
        doc$addTag("expectedValues", close = FALSE)
        #close expected value which encompasses the string value associated with the variable in entry  name
        doc$closeTag()
      }
      
      doc$closeTag() # Model Data Entry
      h = h + 1
    }
    
    doc$closeTag() # data
    doc$closeTag() # models
    doc$closeTag() # component Composition
    cat(saveXML(xml))
    # I want this part to save the entire XML structure to a standalone file but can't find anything that helps.
    
  }
}

names <- list("Taco_DVO", "Taco_TV", "Taco_FLIR")
date <- "2022.10.26"
by <- "Gustafson, T"
name = "Taco_DVO"
tacotuesday <- createXML(name, date, by)
解决方案

你代码里有两个关键问题:一是调用saveXML(xml)时变量名写错了(你创建的XML对象是doc,不是xml);二是没指定输出文件路径,导致只在控制台打印。

下面给你两种可行的修改方案:

方案1:用XML包原生方法保存

把代码里的cat(saveXML(xml))替换成以下代码:

# 生成XML文本内容
xml_text <- saveXML(doc)
# 用当前传感器名称作为文件名,避免文件被覆盖
output_file <- paste0(name[i], ".xml")
# 将内容写入指定文件
writeLines(xml_text, con = output_file)

执行后会在你设置的工作目录下,生成每个传感器对应的XML文件。

方案2:用xml2包的函数保存

既然你已经加载了xml2包,也可以把XML包生成的对象转成xml2格式,再用write_xml保存:

# 转换XML对象格式
xml_doc <- read_xml(saveXML(doc))
# 保存文件
write_xml(xml_doc, file = paste0(name[i], ".xml"))

另外提个小细节:你定义了names列表包含三个传感器,但调用函数时传的是单个name = "Taco_DVO",如果想批量生成三个XML文件,应该改成:

tacotuesday <- createXML(names, date, by)

内容的提问来源于stack exchange,提问作者Work Boi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 14:10:45