我正在使用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>
有什么建议吗?
答案 0 :(得分:4)
总是有点反复试验。你的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