XPath 从子元素中排除文本



>我希望得到输出:

 50ml milk

从以下代码:

<ul class="ingredients-list__group">
  <li>50ml <a href="/glossary/milk" class="tooltip-processed">milk
<div class="tooltip">
      <h2
        class="node-title">Milk</h2> <span class="fonetic">mill-k</span>
        <p>One of the most widely used ingredients, milk is often referred to as a complete food. While cow…</p>
        </div>
        </a>
  </li>
</ul>

目前我正在使用 XPATH:

//ul[@class="ingredients-list__group"]/li

但是得到:

50ml milk Milk mill-kOne of the most widely used ingredients, milk is often referred to as a complete food. While cow… 

如何排除div/工具提示中的内容?

使用 xpath 2.0

//ul[@class="ingredients-list__group"]/li/concat(./text()[1], ./a/text()[1])

xpath 1.0 中:

concat(//ul[@class="ingredients-list__group"]/li/text()[1], //ul[@class="ingredients-list__group"]/li/a/text()[1])'

您可以使用以下方法选择相关文本节点

//ul[@class="ingredients-list__group"]//
   text()[not(ancestor::div[@class='tooltip'])]

如果你在XPath 2.0中,你可以把它放在string-join((的调用中,将它们连接成一个字符串。如果您坚持使用 1.0,则必须将多个文本节点返回到调用应用程序,并在主语言代码中将它们连接在一起。

最新更新