如何使用 xmlValue 制作长度节点的 xpathSApply 输出向量? [英] How to make xpathSApply output vector of length nodes using xmlValue?

查看:27
本文介绍了如何使用 xmlValue 制作长度节点的 xpathSApply 输出向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下内容:

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"

有三个显示"节点.我怎样才能使输出成为:

There are three 'show' nodes. How can I instead make the output be:

# [1] "1.0" NULL "2.0"

为了解释Doctor Who在xml中没有评级但长度仍然是3?

so as to account for Doctor Who not having a rating in the xml but the length still being 3?

推荐答案

如果您提供一直到 'rating' 的路径,节点列表将已经只有 2 个元素开始.因此,当您将 xmlValue() 应用于此节点列表时,输出也将只有 2 个元素.您可以通过从树中的上一层开始来解决这个问题:

If you supply the path all the way to 'rating', the node list will already only have the 2 elements to begin with. So when you apply xmlValue() to this node list, the output will also only have 2 elements. You can get around this by just starting from one level up in the tree:

> xpathSApply(doc, '/tv/show', function(x) xmlValue(xmlChildren(x)$rating))
[1] "1.0" NA    "2.0"

这篇关于如何使用 xmlValue 制作长度节点的 xpathSApply 输出向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆