gpt4 book ai didi

xml - R XML - 尝试将节点添加到内部节点时出错

转载 作者:行者123 更新时间:2023-12-04 18:18:31 24 4
gpt4 key购买 nike

我正在使用 R 和 XML 包读取 XML 文件。我希望读取 XML 文档,执行一些统计计算并将结果作为子节点插入 XML 文档,然后将更新的 XML 文件保存到新位置。

这是一个说明性示例。我正在阅读的 XML 文件(insert_node_error.xml):

<library>
<book>
<title>Book1</title>
<author>AuthorA</author>
</book>
<book>
<title>Book2</title>
<author>AuthorB</author>
</book>
</library>

这是我正在运行的代码:
#load file
file.name <- "xml\\insert_node_error.xml"
input.xml <- xmlInternalTreeParse(file.name)

#produce list of books in library (my actual code has loops and calcs here)
books.xml <- getNodeSet(input.xml, "//book")

#set price for first book as "price" node
price.xml <- xmlNode("price", 19.99)

#attempt to insert that price as child within the first book node
books.xml[[1]] <- addChildren(books.xml[[1]], price.xml)

输出附加了该节点,但已从中剥离了所有 XML,并且仅提供了文本。
> input.xml
<?xml version="1.0"?>
<library>
<book><title>Book1</title><author>AuthorA</author>pricetext19.99</book>
<book>
<title>Book2</title>
<author>AuthorB</author>
</book>
</library>

我想看看:
<library>
<book>
<title>Book1</title>
<author>AuthorA</author>
<price>19.99</price>
</book>
<book>
<title>Book2</title>
<author>AuthorB</author>
</book>
</library>

有什么建议么?

最佳答案

它总是有点反复试验。你的 xmlNode 看起来不错....

library(XML)
#load file
file.name <- "insert_node_error.xml"
input.xml <- xmlInternalTreeParse(file.name)

#produce list of books in library (my actual code has loops and calcs here)
books.xml <- getNodeSet(input.xml, "//book")

price.xml <- xmlNode("price", 19.99)

#set price for first book as "price" node
top = newXMLNode("price",19.99)

#attempt to insert that price as child within the first book node
books.xml[[1]] = addChildren(books.xml[[1]], top)
books.xml

关于xml - R XML - 尝试将节点添加到内部节点时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11209716/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com