R:从XML获取属性值

时间:2014-02-13 08:45:24

标签: xml r

我有一个XML,请参阅下面的示例

<params>
<param id='1'>BEN</param>
<param id='2'>DAN</param>
<param id='3'>RYE</param>
    <param id='3'>RYE</param>
    <param id='3'>RYE</param>
</params>

如何获得属性为id = 3的所有参数?

以下是我到目前为止所做的:xmlinfile是XML文件

inxml = xmlTreeParse(xmlinfile, handlers=list("comment"=function(x,...){NULL}), asTree = TRUE)
xmlList = xmlToList(inxml);
params = xmlList$'params'

非常感谢。

2 个答案:

答案 0 :(得分:2)

您需要使用带有参数xpathApply的函数xmlValue(获取值,否则xmlAttrs获取属性)。路径应使用以下语法给出:"//tag[@attribute='value']"

a <- xmlParse('<params>
<param id='1'>BEN</param>
<param id='2'>DAN</param>
<param id='3'>RYE</param>
    <param id='3'>RYE</param>
    <param id='3'>RYE</param>
</params>')
xpathApply(a,"//param[@id='3']",xmlValue)
[[1]]
[1] "RYE"

[[2]]
[1] "RYE"

[[3]]
[1] "RYE"

同样,xpathSApply会在可能的情况下为您提供值向量:

xpathSApply(a,"//param[@id='3']",xmlValue)
[1] "RYE" "RYE" "RYE"

答案 1 :(得分:0)

xmlinfile <- paste(readLines(n=7), collapse="\n")
<params>
  <param id='1'>BEN</param>
  <param id='2'>DAN</param>
  <param id='3'>RYE</param>
  <param id='3'>RYE</param>
  <param id='3'>RYE</param>
</params>
library(XML)
xpathApply(xmlParse(xmlinfile), "/params/param[@id='3']", xmlValue)  
# [[1]]
# [1] "RYE"
# 
# [[2]]
# [1] "RYE"
# 
# [[3]]
# [1] "RYE