[英]Return blank if the node does not exist in XML using 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>')
你需要先获得带有类描述的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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.