英文:
Open all xml files in a folder and save only few information
问题
我不知道xml是怎么回事,这就是为什么我在这里问的原因。
我正在尝试使用这段代码打开文件夹中的所有XML文件:
library(xml2)
filenames <- list.files("PATH/", pattern="*.xml", full.names=TRUE)
ldf <- lapply(filenames, read_xml)
res <- lapply(ldf, summary)
names(res) <- substr(filenames, 6, 30)
之后我得到了这个:
是否可以为每个ldf创建一个单独的文件?一个ldf对应一个XML。
英文:
I have no idea how xml works and this is why I ask here.
I am trying to open all the XML files in a folder with this code:
library(xml2)
filenames <- list.files("PATH/", pattern="*.xml", full.names=TRUE)
ldf <- lapply(filenames, read_xml)
res <- lapply(ldf, summary)
names(res) <- substr(filenames, 6, 30)
It is possible create a single file for each ldf ? One ldf is one XML
答案1
得分: 1
不确定为什么您想要将它合并为一个单独的文件,但要这样做,您必须创建一个新的XML文档,然后逐个添加每个单独的文件。例如:
library(xml2)
filenames <- list.files("路径/", pattern = ".*\\.xml$", full.names = TRUE)
ldf <- lapply(filenames, read_xml)
doc <- xml_new_root("doc")
for (i in seq_along(ldf)) {
xml_add_child(doc, ldf[[i]])
}
现在 `doc` 是一个包含所有 "ldfs" 的 xml_document 对象。您可以使用 `write_xml(doc, "all_ldfs.xml")` 将该文档保存为一个XML文件。
(我怀疑您真正想要的是从每个文件中提取信息并将其合并为一个单一的数据集?那么请提出一个新问题,其中您提供示例XML文件和您想要提取的信息的解释。)
英文:
Not sure why you would like to combine it into a single file, but to do so you have to make a new xml document and add each separate file in turn. For instance:
library(xml2)
filenames <- list.files("PATH/", pattern = ".*\\.xml$", full.names = TRUE)
ldf <- lapply(filenames, read_xml)
doc <- xml_new_root("doc")
for (i in seq_along(ldf)) {
xml_add_child(doc, ldf[[i]])
}
Now doc
is an xml_document object containing all "ldfs". You can save the document as an xml file using write_xml(doc, "all_ldfs.xml")
.
(My suspicion is that what you really want is to extract information from each file and combine that into a single data set? Then please write a new question where you provide example xml files and an explanation of what information you want to extract.)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论