可以说我有以下内容:
library(XML)
my.xml <- '
<tv>
<show>
<name>Star Trek TNG</name>
<rating>1.0</rating>
</show>
<show>
<name>Doctor Who</name>
</show>
<show>
<name>Babylon 5</name>
<rating>2.0</rating>
</show>
</tv>
'
doc <- xmlParse(my.xml)
xpathSApply(doc, "/tv/show/rating", xmlValue)
# [1] "1.0" "2.0"
Run Code Online (Sandbox Code Playgroud)
有三个'show'节点.我怎样才能使输出为:
# [1] "1.0" NULL "2.0"
Run Code Online (Sandbox Code Playgroud)
为了说明没有在xml中评分但是长度仍为3的Doctor Who?
如果您提供路径一直到'rating',节点列表将只有2个元素开头.因此,当您应用于xmlValue()此节点列表时,输出也将只有2个元素.你可以从树中的一个级别开始解决这个问题:
> xpathSApply(doc, '/tv/show', function(x) xmlValue(xmlChildren(x)$rating))
[1] "1.0" NA "2.0"
Run Code Online (Sandbox Code Playgroud)