【问题标题】:R XML - Error attemping to add Node to Internal NodeR XML - 尝试将节点添加到内部节点时出错
【发布时间】:2012-06-27 21:52:39
【问题描述】:

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

有什么建议吗?

【问题讨论】:

    标签: xml r


    【解决方案1】:

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

    【讨论】:

    • Dieter -- 非常感谢!完美运行,我不确定我是否会找到/考虑过 newXMLNode 函数。干杯!
    • Dieter -- 这样做了。无法标记为有用,因为我没有声誉。
    • 你有!你的问题是完美的,应该给予额外的信任。与我们保持联系。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-16
    • 2020-08-25
    • 2021-07-27
    • 1970-01-01
    相关资源
    最近更新 更多