如何使用HTML Agility Pack?
我的XHTML文档不是完全有效。这就是为什么我要使用它。如何在项目中使用它?我的项目在C#中。
首先,将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实体的另一种有用方法。
HtmlEntity.DeEntitize()
HtmlDocument这HtmlNode是您最常使用的类。与XML解析器类似,它提供了接受XPath表达式的selectSingleNode和selectNodes方法。
HtmlDocument
HtmlNode
注意HtmlDocument.Option??????布尔属性。这些控制Load和LoadXML方法处理HTML / XHTML的方式。
HtmlDocument.Option??????
还有一个名为HtmlAgilityPack.chm的已编译帮助文件,该文件对每个对象都有完整的引用。这通常在解决方案的基本文件夹中。
HtmlAgilityPack.chm