HtmlAgilityPack选择子节点值

本文关键字:子节点 选择 HtmlAgilityPack | 更新日期: 2023-09-27 18:10:23

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>

我想从一个分区检索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;

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

HtmlAgilityPack选择子节点值

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']

工作演示示例:

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']