HtmlAgilityPack select 子节点值

HtmlAgilityPack select subnodes value

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;

Exception: Object reference not set to an instance of an object. Cant figure out the correct syntax Appreciate your help

div[@class='pha d-k-l'] 不是 div[@class='XKa d-k-l'] 的后代,关系是 siblings 而不是 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']