DocumentFactory
Provides the default content-type to document creation mapping.
using AngleSharp.Dom;
using AngleSharp.Dom.Html;
using AngleSharp.Dom.Svg;
using AngleSharp.Dom.Xml;
using AngleSharp.Network;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace AngleSharp.Services.Default
{
public class DocumentFactory : IDocumentFactory
{
public delegate Task<IDocument> Creator (IBrowsingContext context, CreateDocumentOptions options, CancellationToken cancellationToken);
private readonly Dictionary<string, Creator> _creators = new Dictionary<string, Creator> {
{
MimeTypeNames.Xml,
XmlDocument.LoadAsync
},
{
MimeTypeNames.ApplicationXml,
XmlDocument.LoadAsync
},
{
MimeTypeNames.Svg,
SvgDocument.LoadAsync
},
{
MimeTypeNames.Html,
HtmlDocument.LoadAsync
},
{
MimeTypeNames.ApplicationXHtml,
HtmlDocument.LoadAsync
},
{
MimeTypeNames.Plain,
HtmlDocument.LoadTextAsync
},
{
MimeTypeNames.ApplicationJson,
HtmlDocument.LoadTextAsync
},
{
MimeTypeNames.DefaultJavaScript,
HtmlDocument.LoadTextAsync
},
{
MimeTypeNames.Css,
HtmlDocument.LoadTextAsync
}
};
public void Register(string contentType, Creator creator)
{
_creators.Add(contentType, creator);
}
public Creator Unregister(string contentType)
{
Creator value = null;
if (_creators.TryGetValue(contentType, out value))
_creators.Remove(contentType);
return value;
}
protected virtual Task<IDocument> CreateDefaultAsync(IBrowsingContext context, CreateDocumentOptions options, CancellationToken cancellationToken)
{
return HtmlDocument.LoadAsync(context, options, cancellationToken);
}
public Task<IDocument> CreateAsync(IBrowsingContext context, CreateDocumentOptions options, CancellationToken cancellationToken)
{
MimeType contentType = options.ContentType;
foreach (KeyValuePair<string, Creator> creator in _creators) {
if (contentType.Represents(creator.Key))
return creator.Value(context, options, cancellationToken);
}
return CreateDefaultAsync(context, options, cancellationToken);
}
}
}