如果使用R在XML中不存在该节点,则返回空白

时间:2014-05-04 17:53:51

标签: xml r

我需要支持才能解决这个问题:

我想在R中编写一个代码,如果相应的

节点存在则返回“今天是星期天”,否则我想返回“”。

我正在使用以下代码

Man<-unlist(xpathApply(doc,"//div[@class='description']//p[not(@*)]//tt[@class='notranslate']", xmlValue))

I am getting: [1] "It is sunday today"
but I am expecting: [1] "It is sunday today"
                    [2] ""    

请帮助我如何编写R代码以获得预期的输出

以下是我的XML:

doc <- (
'<div class="description">
   <p>
    <strong>Advice to Senior Management</strong>
    –
    <tt class="notranslate">It is sunday today</tt>
    </p>
    <p class="nep">
     <strong>No, I would not recommend </strong>
     – I'm not optimistic 
    </p>
  </div>
  <div class="description">
    <p class="nep">
     <strong>No, I would not recommend </strong>
     – I'm not optimistic 
    </p>
  </div>')

1 个答案:

答案 0 :(得分:3)

您需要先获取带有类描述的div。您可以使用getNodeSet或简写

执行此操作
doc["//div[@class='description']"]

拥有这些节点后,您可以检查子节点是否有适当的xpath

lapply(doc["//div[@class='description']"], function(x){
  xpathSApply(x, ".//p[not(@*)]//tt[@class='notranslate']", xmlValue)
}
)
> lapply(doc["//div[@class='description']"], function(x){xpathSApply(x, ".//p[not(@*)]//tt[@class='notranslate']", xmlValue)})
[[1]]
[1] "It is sunday today"

[[2]]
NULL