首页 > 解决方案 > 将 xml_node 列表转换为 xml_document

问题描述

我有一个 xml_node 项目列表(nodes_list在下面的表示中),我想将它们组合成一个带有根节点bookstore_doc的 xml_document(在下面的表示中)。

我当前的解决方案是创建一个xml_new_root()并遍历我的 xml_node 项目列表xml_add_child()。虽然这有效,但它非常慢!大约 6,000 个节点花费了 9 个多小时。我想这部分是由于 for 循环,我试图用 , 替换它purrr::map()purrr::walk()或者这些循环sapply()不能正常工作。我猜想有一种比迭代遍历 xml_node 项目列表更计算有效的方法,但我不确定是什么,因为我仍然是使用 xml 的新手。

对于如何更有效地将 xml_node 项目列表转换为单个 xml_document 的任何想法,我将不胜感激。

感谢您的时间和建议!

library(xml2)

# Create data for minimal reproducible example
text_1 <- "
  <book>
    <title lang='en'>Harry Potter</title>
    <author>J K. Rowling</author>
    <year>2005</year>
    <price>29.99</price>
  </book>
"

text_2 <- "
  <book>
    <title lang='en'>Learning XML</title>
    <price>39.95</price>
    info
  </book>
"

node_1 <- xml_find_first(read_xml(text_1), "//book")
node_2 <- xml_find_first(read_xml(text_2), "//book")

nodes_list <- list(node_1, node_2)

# Current method for generating xml_document
bookstore_doc <- xml_new_root("bookstore")

for (book in nodes_list) {
  xml_add_child(bookstore_doc, book)
}

由来自https://www.w3schools.com/xml/xpath_nodes.asp的reprex 包(v0.3.0) Book 节点创建于 2020 年 6 月 15 日

相关的 SO 问题 在 R 中,如何将两个 XML 文档合并为一个文档?

标签: rxmlpurrrxml2

解决方案


一种选择不是逐个添加节点,而是将所需的文档结构构建为 R 列表,然后将其转换为 xml 文档。关键是确保节点都被命名:

node_names <- rep("book", length(nodes_list))
as_xml_document(list(books = setNames(lapply(nodes_list, as_list), node_names)))
#> {xml_document}
#> <books>
#> [1] <book>\n  <title lang="en">Harry Potter</title>\n  <author>J K. Rowling</author>\n  ..
#> [2] <book><title lang="en">Learning XML</title><price>39.95</price>\n    info\n  </book>

推荐阅读