打开文件夹中的所有 XML 文件并仅保存少量信息。

huangapple go评论70阅读模式
英文:

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)

之后我得到了这个:

打开文件夹中的所有 XML 文件并仅保存少量信息。

是否可以为每个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 &lt;- list.files(&quot;PATH/&quot;, pattern=&quot;*.xml&quot;, full.names=TRUE)
ldf &lt;- lapply(filenames, read_xml)
res &lt;- lapply(ldf, summary)
names(res) &lt;- substr(filenames, 6, 30)

After that I have this:
打开文件夹中的所有 XML 文件并仅保存少量信息。

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 &lt;- list.files(&quot;PATH/&quot;, pattern = &quot;.*\\.xml$&quot;, full.names = TRUE)

ldf &lt;- lapply(filenames, read_xml)

doc &lt;- xml_new_root(&quot;doc&quot;)

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, &quot;all_ldfs.xml&quot;).

(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.)

huangapple
  • 本文由 发表于 2023年3月8日 16:54:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/75671018.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定