我有一个xml_node项目的列表(nodes_list
在下面的reprex中),我想把它们合并成一个带有根节点的xml_document (bookstore_doc
在下面的reprex中)。)
我现在的解决方案是创建一个 xml_new_root()
并在我的xml_node项目列表中用 xml_add_child()
. 虽然这个工作,它是非常缓慢的! 花了9个多小时来处理大约6000个节点。我猜想这部分是由于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)
}
创建于 2020-06-15 由 重读包 (v0.3.0)书籍节点从 https:/www.w3schools.comxmlxpath_nodes.asp
有一种方法比逐个添加节点更适合,那就是将所需的文档结构建立为一个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>