如何使用HtmlAgilityPack在C#中获取HTML元素的内容?

6
我想要使用HTMLAgilityPack在C#中获取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;
}
2个回答

4
以下代码对我有效:
```html

以下代码对我有效:

```
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;
}

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

(未经测试,凭记忆)

很好的回答。已投票支持。 - koolprasad2003

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接