HtmlParser
Creates an instance of the HTML parser front-end.
using AngleSharp.Dom;
using AngleSharp.Dom.Html;
using AngleSharp.Extensions;
using AngleSharp.Services;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace AngleSharp.Parser.Html
{
public class HtmlParser
{
private readonly HtmlParserOptions _options;
private readonly IBrowsingContext _context;
public HtmlParserOptions Options => _options;
public IBrowsingContext Context => _context;
public HtmlParser()
: this(Configuration.Default)
{
}
public HtmlParser(HtmlParserOptions options)
: this(options, Configuration.Default)
{
}
public HtmlParser(IConfiguration configuration)
: this(new HtmlParserOptions {
IsScripting = configuration.IsScripting()
}, configuration)
{
}
public HtmlParser(HtmlParserOptions options, IConfiguration configuration)
: this(options, BrowsingContext.New(configuration))
{
}
public HtmlParser(HtmlParserOptions options, IBrowsingContext context)
{
_options = options;
_context = context;
}
public IHtmlDocument Parse(string source)
{
return new HtmlDomBuilder(CreateDocument(source)).Parse(_options);
}
public INodeList ParseFragment(string source, IElement context)
{
HtmlDocument htmlDocument = CreateDocument(source);
HtmlDomBuilder htmlDomBuilder = new HtmlDomBuilder(htmlDocument);
if (context != null) {
Element element = context as Element;
if (element == null)
element = htmlDocument.Options.GetFactory<IElementFactory<HtmlElement>>().Create(htmlDocument, context.LocalName, context.Prefix);
return htmlDomBuilder.ParseFragment(_options, element).DocumentElement.ChildNodes;
}
return htmlDomBuilder.Parse(_options).ChildNodes;
}
public IHtmlDocument Parse(Stream source)
{
return new HtmlDomBuilder(CreateDocument(source)).Parse(_options);
}
public Task<IHtmlDocument> ParseAsync(string source)
{
return ParseAsync(source, CancellationToken.None);
}
public Task<IHtmlDocument> ParseAsync(Stream source)
{
return ParseAsync(source, CancellationToken.None);
}
public async Task<IHtmlDocument> ParseAsync(string source, CancellationToken cancel)
{
return await new HtmlDomBuilder(CreateDocument(source)).ParseAsync(_options, cancel).ConfigureAwait(false);
}
public async Task<IHtmlDocument> ParseAsync(Stream source, CancellationToken cancel)
{
return await new HtmlDomBuilder(CreateDocument(source)).ParseAsync(_options, cancel).ConfigureAwait(false);
}
private HtmlDocument CreateDocument(string source)
{
TextSource textSource = new TextSource(source);
return CreateDocument(textSource);
}
private HtmlDocument CreateDocument(Stream source)
{
TextSource textSource = new TextSource(source, _context.Configuration.DefaultEncoding());
return CreateDocument(textSource);
}
private HtmlDocument CreateDocument(TextSource textSource)
{
return new HtmlDocument(_context, textSource);
}
}
}