HtmlAgilityPack选择子节点值

时间:2015-08-29 06:13:40

标签: c# xpath html-agility-pack

HTML字符串包含确切的字符串

<div class="XKa d-k-l"><span class="VTb d-k-l"></span></div><div class="pha d-k-l"><div ><div>Hello World </div>

我想从div中检索Hello World。

我正在使用HtmlAgilityPack

var item = 
     HTMLContent.DocumentNode
                .SelectSingleNode("//div[@class='XKa d-k-l']//span[@class='VTb d-k-l']//div[@class='pha d-k-l']")
                .InnerHtml;
  

异常:对象引用未设置为对象的实例。无法找出正确的语法感谢您的帮助

1 个答案:

答案 0 :(得分:0)

div[@class='pha d-k-l']不是div[@class='XKa d-k-l']的后代,关系是sibling而不是ancestor - descendant。您可以尝试使用following-sibling轴,如下所示:

//div[@class='XKa d-k-l']/following-sibling::div[@class='pha d-k-l']

working demo example

var html = @"<div class='XKa d-k-l'><span class='VTb d-k-l'></span></div><div class='pha d-k-l'><div><div>Hello World </div></div></div>";
var HTMLContent = new HtmlDocument();
HTMLContent.LoadHtml(html);
var item = HTMLContent.DocumentNode
            .SelectSingleNode("//div[@class='XKa d-k-l']/following-sibling::div[@class='pha d-k-l']").InnerHtml;
Console.WriteLine(item);

输出

<div><div>Hello World </div></div>

更新:

您可以像这样添加span支票:

//div[@class='XKa d-k-l'][span/@class='VTb d-k-l']/following-sibling::div[@class='pha d-k-l']