使用Xpath和HtmlAgilityPack查找包含特定单词或单词的innertext的所有元素

use*_*569 5 xpath html-agility-pack

我正在尝试使用HtmlAgilityPack和Xpath与C#(.NET 4)构建一个简单的搜索引擎.我想找到包含用户定义的搜索词的每个节点,但我似乎无法使XPath正确.例如:

<HTML>
 <BODY>
  <H1>Mr T for president</H1>
   <div>We believe the new president should be</div>
   <div>the awsome Mr T</div>
   <div>
    <H2>Mr T replies:</H2>
     <p>I pity the fool who doesn't vote</p>
     <p>for Mr T</p>
   </div>
  </BODY>
</HTML>
Run Code Online (Sandbox Code Playgroud)

如果指定的搜索内容是"T先生"我想以下节点:<H1>,第二<div>,<H2>和第二<p>.我尝试了很多变种,doc.DocumentNode.SelectNodes("//text()[contains(., "+ searchword +")]");但我似乎总是在整个DOM中的每一个节点.

任何暗示让我走向正确的方向将非常感激.

Dim*_*hev 12

用途:

//*[text()[contains(., 'Mr T')]]
Run Code Online (Sandbox Code Playgroud)

这将选择XML文档中具有包含字符串的text-node子元素的所有元素'Mr T'.

这也可以写得更短:

//text()[contains(., 'Mr T')]/..
Run Code Online (Sandbox Code Playgroud)

这将选择包含该字符串的任何文本节点的父节点'Mr T'.