节点选择 - 当前节点深度的两个标签

时间:2015-04-01 18:10:06

标签: xpath html-agility-pack

我正在使用HTML Agility Pack。我有一个HTMLNode,其中包含以下InnerHtml:

"Item: <b><a href="item.htm">Link Text</a></b>"

从这个节点,我想选择&#34; Link Text&#34;来自&#34; a&#34;标签。我无法做到这一点。我试过这个:

System.Diagnostics.Debug.WriteLine(node.InnerHtml);
//The above line prints "Item: <b><a href="item.htm">Link Text</a></b>"
HtmlNode boldTag = node.SelectSingleNode("b");
if (boldTags != null)
{
    HtmlNode linkTag = boldTag.SelectSingleNode("a");
    //This is always null!
    if (linkTag != null)
    {
        return linkTag.InnerHtml;           
    }
}

任何有助于选择正确的帮助都将不胜感激。

1 个答案:

答案 0 :(得分:1)

SelectSingleNode需要XPath

所以你需要

 var b = htmlDoc.DocumentNode.SelectSingleNode("//b");
 var a = b.SelectSingleNode("./a");
 var text = a.InnerText;

在一行

var text =  htmlDoc.DocumentNode.SelectSingleNode("//b/a").InnerText;

请注意,在xpath的开头

  • //将查找DocumentNode中的任何位置
  • .//将查找当前节点的后代
  • /将寻找DocumentNode的孩子
  • ./将查找当前节点的子节目
相关问题