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

在Xamarin Android中使用HtmlAgilityPack获取第二个HTML元素文本

获取第二个HTML元素的文本(HtmlAgilityPack + Xamarin Android)

你现在的代码会把所有匹配的<li>元素文本拼接起来,但要单独拿到第二个元素的内容,其实有两种简单的方法可以实现:

方法1:通过集合索引直接访问

HtmlNodeCollection本身支持索引访问(从0开始计数),所以第二个元素对应的索引是1。记得先判断集合是否为空、长度是否足够,避免空引用或索引越界异常:

void Btn_Click(object sender, System.EventArgs e) {
    HtmlWeb hw = new HtmlWeb();
    HtmlDocument document = hw.Load("https://broncoshuttle.com/simple/routes/3164/stops/36359");
    HtmlNodeCollection nodes = document.DocumentNode.SelectNodes("//ul//li");
    
    if (nodes != null && nodes.Count >= 2)
    {
        // 取第二个元素(索引1)的InnerText,Trim去掉多余空格
        string result = nodes[1].InnerText.Trim();
        MyTextView.Text = result;
    }
    else
    {
        // 处理元素不存在的情况
        MyTextView.Text = "No arrival prediction info found";
    }
}

方法2:用XPath直接定位第二个元素

你也可以直接在XPath表达式里指定要选第二个<li>元素,这样不需要遍历整个集合,效率更高:

void Btn_Click(object sender, System.EventArgs e) {
    HtmlWeb hw = new HtmlWeb();
    HtmlDocument document = hw.Load("https://broncoshuttle.com/simple/routes/3164/stops/36359");
    // 用[2]定位第二个li元素(XPath里的位置从1开始计数)
    HtmlNode targetNode = document.DocumentNode.SelectSingleNode("//ul//li[2]");
    
    if (targetNode != null)
    {
        string result = targetNode.InnerText.Trim();
        MyTextView.Text = result;
    }
    else
    {
        MyTextView.Text = "No arrival prediction info found";
    }
}

小提示

  • 注意XPath的位置计数是从1开始的,而C#集合的索引是从0开始的,别搞混了!
  • 一定要加空值判断,万一网页结构变化或者元素不存在,你的App不会崩溃。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:17:06