我该如何使用HTML 敏捷包 http://html-agility-pack.net/?z=codeplex?
我的 XHTML 文档不完全有效。这就是我想使用它的原因。我如何在我的项目中使用它?我的项目是用 C# 编写的。
首先,安装HTML敏捷包 https://www.nuget.org/packages/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
}
}
}
(注意:此代码只是一个示例,不一定是最好/唯一的方法。不要在您自己的应用程序中盲目使用它。)
The HtmlDocument.Load()
方法还接受一个流,这对于与 .NET 框架中其他面向流的类集成非常有用。尽管HtmlEntity.DeEntitize()
是正确处理 html 实体的另一种有用方法。 (感谢马修)
HtmlDocument
and HtmlNode
是您最常使用的类。与 XML 解析器类似,它提供接受 XPath 表达式的 selectSingleNode 和 selectNodes 方法。
注意HtmlDocument.Option??????
布尔属性。这些控制如何Load
and LoadXML
方法将处理您的 HTML/XHTML。
还有一个名为 HtmlAgilityPack.chm 的已编译帮助文件,其中包含每个对象的完整参考。这通常位于解决方案的基本文件夹中。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)