2

我正在使用 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>

有什么建议么?

4

1 回答 1

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
于 2012-06-26T15:43:06.333 回答