小编典典

如何使用HTML Agility Pack

php

如何使用HTML Agility Pack?

我的XHTML文档不是完全有效。这就是为什么我要使用它。如何在项目中使用它?我的项目在C#中。


阅读 910

收藏
2020-05-13

共1个答案

小编典典

首先,将HTMLAgilityPack nuget软件包安装到您的项目中。

然后,例如:

HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();

// There are various options, set as needed
htmlDoc.OptionFixNestedTags=true;

// filePath is a path to a file containing the html
htmlDoc.Load(filePath);

// Use:  htmlDoc.LoadHtml(xmlString);  to load from a string (was htmlDoc.LoadXML(xmlString)

// ParseErrors is an ArrayList containing any errors from the Load statement
if (htmlDoc.ParseErrors != null && htmlDoc.ParseErrors.Count() > 0)
{
    // Handle any parse errors as required

}
else
{

    if (htmlDoc.DocumentNode != null)
    {
        HtmlAgilityPack.HtmlNode bodyNode = htmlDoc.DocumentNode.SelectSingleNode("//body");

        if (bodyNode != null)
        {
            // Do something with bodyNode
        }
    }
}

(注意:此代码仅是示例,不一定是最佳/唯一方法。请不要在自己的应用程序中盲目使用它。)

该HtmlDocument.Load()方法还接受一个流,该流在与.NET框架中的其他面向流的类集成时非常有用。虽然HtmlEntity.DeEntitize()是正确处理html实体的另一种有用方法。

HtmlDocumentHtmlNode是您最常使用的类。与XML解析器类似,它提供了接受XPath表达式的selectSingleNode和selectNodes方法。

注意HtmlDocument.Option??????布尔属性。这些控制Load和LoadXML方法处理HTML / XHTML的方式。

还有一个名为HtmlAgilityPack.chm的已编译帮助文件,该文件对每个对象都有完整的引用。这通常在解决方案的基本文件夹中。

2020-05-13