如何使用 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 实体的有用方法。 (感谢马修)
HtmlDocument
和 HtmlNode
是您最常使用的类。类似于 XML 解析器,它提供了接受 XPath 表达式的 selectSingleNode 和 selectNodes 方法。
注意HtmlDocument.Option??????
bool 属性。这些控制 Load
和 LoadXML
方法如何处理您的 HTML/XHTML。
还有一个名为 HtmlAgilityPack.chm 的已编译帮助文件,其中包含每个对象的完整引用。这通常位于解决方案的基本文件夹中。
https://stackoverflow.com/questions/846994/