مراحل زیر بهترتیب برای افزودن کامل Extractor HTML به پروژه xAiApi انجام میشود:
گام ۱ — نصب بسته NuGet
در فایل xAiApi.csproj، بسته زیر را اضافه کنید:
<PackageReference Include="AngleSharp" Version="1.1.2" />
یا از طریق .NET CLI:
dotnet add package AngleSharp
💡 نکته: AngleSharp هیچ وابستگی Native ندارد و در تمام محیطهای Linux، macOS و Windows کار میکند. نیازی به نصب بسته اضافی برای Docker نیست.
گام ۲ — ایجاد اینترفیس اختصاصی
فایل Interfaces/Extractors/IXHtmlFileContentExtractor.cs را با محتوای نشاندادهشده در بخش ۳ ایجاد کنید.
گام ۳ — پیادهسازی کلاس اصلی
فایل Providers/Extractors/XHtmlFileContentExtractor.cs را ایجاد کنید:
using System;
using System.IO;
using System.Linq;
using AngleSharp;
using System.Text;
using System.Threading;
using AngleSharp.Html.Parser;
using xAiModels.Models;
using System.Threading.Tasks;
using xAiApi.Interfaces.Extractors;
namespace xAiApi.Providers.Extractors
{
/// <summary>
/// Extracts clean text content from HTML documents
/// (text/html, application/xhtml+xml) using AngleSharp.
/// </summary>
public class XHtmlFileContentExtractor : IXHtmlFileContentExtractor
{
/// <summary>
/// Supported MIME Types ...
/// </summary>
private static readonly string[] SupportedMimeTypes =
[
"text/html",
"application/xhtml+xml"
];
/// <summary>
/// Check if this extractor supports the specified MIME type ...
/// </summary>
public bool CanExtract(string mimeType)
{
return SupportedMimeTypes.Contains(
mimeType?.ToLowerInvariant() ?? string.Empty
);
}
/// <summary>
/// Extract text content from file stream ...
/// </summary>
public async Task<string> ExtractAsync(
Stream fileStream,
string mimeType,
CancellationToken cancellationToken = default)
{
var result = await ExtractRichAsync(
fileStream, "document.html", mimeType, cancellationToken
);
return result.Text;
}
/// <summary>
/// Extract content from stream as Rich Result ...
/// </summary>
public async Task<XFileExtractionResult> ExtractRichAsync(
Stream fileStream,
string fileName,
string mimeType,
CancellationToken cancellationToken = default)
{
var result = new XFileExtractionResult
{
FileName = fileName,
MimeType = mimeType
};
try
{
// Copy to MemoryStream (AngleSharp requires seekable stream)
await using var ms = new MemoryStream();
await fileStream.CopyToAsync(ms, cancellationToken);
ms.Position = 0;
// Read HTML content with encoding detection
using var reader = new StreamReader(ms, Encoding.UTF8, true);
var html = await reader.ReadToEndAsync();
// Parse HTML with AngleSharp
var parser = new HtmlParser();
using var document = await parser.ParseDocumentAsync(
html, cancellationToken
);
// Extract document title
var title = document.Title?.Trim();
if (!string.IsNullOrWhiteSpace(title))
{
result.Text = $"Title: {title}{Environment.NewLine}{Environment.NewLine}";
}
// Extract visible body text
// TextContent excludes