【问题标题】:Parse an XML file and return an R character vector解析 XML 文件并返回 R 字符向量
【发布时间】:2012-07-12 15:45:33
【问题描述】:

我已经用 R 解析了一个 XML 文档,例如:

library(XML)
f = system.file("exampleData", "mtcars.xml", package="XML")
doc = xmlParse(f)

使用 XPath 表达式,我可以选择文档中的特定节点:

> getNodeSet(doc, "//record[@id='Mazda RX4']/text()")
[[1]]
   21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4 

    attr(,"class")
    [1] "XMLNodeSet"

但我不知道如何将结果转换为 R 字符向量:

> as.character(getNodeSet(doc, "//record[@id='Mazda RX4']/text()"))
[1] "<pointer: 0x000000000e6a7fe0>"

如何从指向 C 对象的内部指针获取文本?

【问题讨论】:

    标签: xml r


    【解决方案1】:

    使用xmlValue。这是您示例的扩展,可帮助您了解类是什么:

    v <- getNodeSet(doc, "//record[@id='Mazda RX4']/text()")
    str(v)
    #List of 1
    #$ :Classes 'XMLInternalTextNode', 'XMLInternalNode', 'XMLAbstractNode' <externalptr> 
    #- attr(*, "class")= chr "XMLNodeSet"
    v2 <- sapply(v, xmlValue)  #this is the code chunk of interest to you
    v2
    #[1] "   21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4"
    str(v2)
    #chr "   21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4"
    

    【讨论】:

      【解决方案2】:

      以下也将起作用: 代替 getNodeSet() 和 sapply(v,xmlValue),您可以使用 xpathApply 并将 xmlValue 添加为参数

      doc = xmlParse(f)
      xpathApply(doc,"//record[@id='Mazda RX4']/text()")
      
      [[1]]
         21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4 
      
      attr(,"class")
      [1] "XMLNodeSet"
      
      xpathApply(doc,"//record[@id='Mazda RX4']/text()",xmlValue)
      
      [[1]]
      [1] "   21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4"
      

      这是一个列表中的字符对象。您可以通过取消列出、使用一个或多个空格的正则表达式拆分字符串、再次取消列出和 as.numeric()

      将其转换为数字对象的向量
       as.numeric(unlist(strsplit(unlist(v)," +")))
       [1]     NA  21.00   6.00 160.00 110.00   3.90   2.62  16.46   0.00   1.00   4.00   4.00
      

      【讨论】:

        猜你喜欢
        • 2013-03-26
        • 1970-01-01
        • 2012-05-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-16
        • 1970-01-01
        相关资源
        最近更新 更多