You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

HtmlAgilityPack如何获取全部匹配节点而非仅FirstOrDefault返回的首个节点

解决方案

你当前代码中调用的FirstOrDefault()作用是提取序列的首个元素,去掉该方法即可拿到所有匹配的<a>节点集合,再遍历集合逐个提取href属性值即可。以下是两种常用实现方式:

方法1:基础遍历写法(可读性更高)

List<string> allHrefs = new List<string>();
// 先获取目标区域下所有<a>节点集合
var aNodes = doc.DocumentNode.SelectNodes("//*[@id=\"announcementsContainer\"]/div[1]/div[2]")?.Descendants("a");

if (aNodes != null)
{
    foreach (var aNode in aNodes)
    {
        // 过滤掉没有href属性的节点,避免空引用异常
        if (aNode.Attributes["href"] != null)
        {
            allHrefs.Add(aNode.Attributes["href"].Value);
        }
    }
}

方法2:LINQ简化写法

List<string> allHrefs = doc.DocumentNode
    .SelectNodes("//*[@id=\"announcementsContainer\"]/div[1]/div[2]")?
    .Descendants("a")
    .Where(node => node.Attributes["href"] != null)
    .Select(node => node.Attributes["href"].Value)
    .ToList() ?? new List<string>();

两种写法最终得到的allHrefs列表就存储了所有符合条件的href属性值,写法中额外增加了空值判断逻辑,避免节点不存在、属性不存在时抛出空引用异常。

内容的提问来源于stack exchange,提问作者ItsYeBoi2016

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 04:06:02