如何在 C# 中将 HTML 转换为文本

这个简单的操作方法演示了如何HTML 转换为 C# 中的文本。在 *C# 中,HTML 到纯文本 * 的转换可以通过对在 Windows、macOS 或 Linux 平台上运行的任何基于 .NET 的应用程序使用几行代码轻松实现。

在 C# 中将 HTML 转换为文本的步骤

  1. 从 NuGet 包管理器安装 Aspose.HTML for .NET
  2. 在您的项目中包含 Aspose.HTML 命名空间
  3. 将 HTML 文件内容加载到字符串
  4. 创建 HTMLDocument 类的实例以加载包含 HTML 的字符串
  5. 实例化 INodeIterator 类实例以遍历节点并附加到 StringBuilder
  6. 最后,将转换后的 HTML 文本保存在磁盘上

为了从 HTML C# 中获取纯文本,可以在任何基于 .NET 的应用程序中有效地使用几行代码。该过程首先使用 File.ReadAllText 方法将 HTML 文件作为字符串加载到 HTMLDocument 类 实例中。然后 INodeIterator 将用于从 HTML 中提取节点并将它们附加到 StringBuilder。最后,StringBuilder 中提取的 HTML 将保存在磁盘上。

在 C# 中将 HTML 转换为文本的代码

using System;
using System.IO;
using System.Text;
using Aspose.Html;
using Aspose.Html.Dom.Traversal;
using Aspose.Html.Dom.Traversal.Filters;
namespace KbHtml
{
class Program
{
static void Main(string[] args)
{
// Set the API license to extract HTML text
License license = new License();
license.SetLicense("Aspose.Html.lic");
// Reading HTML file content
String HtmlContent = File.ReadAllText("Test2.html");
// Create an object of HTMLDocument
using (var HtmlDocument = new HTMLDocument(HtmlContent, ""))
{
// Initialize the instance of node iterator to iterate HTML
INodeIterator iterator = HtmlDocument.CreateNodeIterator(HtmlDocument, NodeFilter.SHOW_TEXT,
new StyleFilter());
StringBuilder Stringbld = new StringBuilder();
Aspose.Html.Dom.Node node;
// Iterate through Nodes
while ((node = iterator.NextNode()) != null)
Stringbld.Append(node.NodeValue);
Console.WriteLine(Stringbld.ToString());
File.WriteAllText(@"HtmlToText.txt", Stringbld.ToString());
}
}
}
class StyleFilter : NodeFilter
{
public override short AcceptNode(Aspose.Html.Dom.Node node)
{
// In order to avoid any element during fetching nodes, write the name of element in capital letters
return (node.ParentElement.TagName == "STYLE" || node.ParentElement.TagName == "SCRIPT"
? FILTER_REJECT : FILTER_ACCEPT);
}
}
}

C# 中的上述代码使用少量 API 调用将 HTML 转换为纯文本。我们使用了自定义的StyleFilter 类,它继承了NodeFilter 类 来覆盖AcceptNode 方法,该方法在转换过程中从HTML 中过滤掉不需要的节点。

在上一主题中,我们学习了如何在 C# 中创建 HTML 文件。而上面 C# 中的示例以编程方式从 HTML 文件中获取纯文本。

 简体中文