【问题标题】:How to get the contents of a HTML element using HtmlAgilityPack in C#?如何在 C# 中使用 HtmlAgilityPack 获取 HTML 元素的内容?
【发布时间】:2011-05-20 12:15:57
【问题描述】:

我想在 C# 中使用 HTMLAgilityPack 从 HTML 页面获取有序列表的内容,我尝试了以下代码,但是这不起作用,谁能帮忙,我想传递 html 文本并获取在 html 中找到的第一个有序列表

private bool isOrderedList(HtmlNode node)
{
    if (node.NodeType == HtmlNodeType.Element)
    {
        if (node.Name.ToLower() == "ol")
            return true;
        else
            return false;
    }
    else
        return false;
}

public string GetOlList(string htmlText)
{
    string s="";
    HtmlDocument doc = new HtmlDocument();
    doc.LoadHtml(htmlText);
    HtmlNode nd = doc.DocumentNode;
    foreach (HtmlNode node in nd.ChildNodes)
    {
        if (isOrderedList(node))
        {
            s = node.WriteContentTo();
            break;
        }
        else if (node.HasChildNodes)
        {
            string sx= GetOlList(node.WriteTo());
            if (sx != "")
            {
                s = sx;
                break;
            }
        }
    }
    return s;
}

【问题讨论】:

    标签: c# html html-parsing html-agility-pack


    【解决方案1】:

    以下代码对我有用

    public static string GetComments(string html)
    {
        HtmlDocument doc = new HtmlDocument();
        doc.LoadHtml(html);
        string s = "";
        foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//ol"))
        {
            s += node.OuterHtml;
        }
    
        return s;
    }
    

    【讨论】:

      【解决方案2】:

      怎么样:

      var el = (HtmlElement)doc.DocumentNode
          .SelectSingleNode("//ol");
      if(el!=null)
      {
          string s = el.OuterHtml;
      }
      

      (未经测试,凭记忆)

      【讨论】:

      • 不错的答案。投票赞成
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-13
      相关资源
      最近更新 更多