2012-06-26 26 views
2

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

这总是有点反复试验。你的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 
+0

迪特 - 非常感谢你!完美的工作,我不知道我会发现/考虑newXMLNode函数。干杯! – downtowater

+0

如果您需要它,您应该将其标记为答案。 –

+0

迪特 - 这样做。不能标记为有用,因为我没有名誉。 – downtowater