//在XPath中的parent :: *?

时间:2018-02-08 14:22:45

标签: r xml xpath xml2

考虑这个简单的例子

<div class="custom-upload">
  <div class="file-upload">
    <div class="file-select">
      <div class="file-select-button" id="fileName">kies foto</div>
      <div class="file-select-name" id="noFile">geen foto gekozen</div>
      <input type="file" name="attach8" id="chooseFile">
    </div>
   </div>
  </div>

现在,我想找到包含字符串library(xml2) x <- read_xml("<body> <p>Some <b>text</b>.</p> <p>Some <b>other</b> <b>text</b>.</p> <p>No bold here!</p> </body>") 的节点的所有父节点 为此,我运行

other

我不明白为什么我也得到> xml_find_all(x, "//b[contains(.,'other')]//parent::*") {xml_nodeset (2)} [1] <p>Some <b>other</b> <b>text</b>.</p> [2] <b>other</b> 元素。在我看来,只有一个父节点,它是第一个节点。

这是一个错误吗?

1 个答案:

答案 0 :(得分:1)

更改

//b[contains(.,'other')]//parent::*

选择 descendant-or-self (并且您不希望 self )和 parent

//b[contains(.,'other')]/parent::*

纯粹沿选择,以从选择中消除<b>other</b>

或者,更好的是,使用此XPath:

//p[b[contains(.,'other')]]

如果要选择所有p个元素,其中b子元素的字符串值包含“其他”子字符串,或者

//p[b = 'other']

如果b的字符串值应该等于 other。另请参阅What does contains() do in XPath?