Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to build AngleSharp CSS (or HTML) DOM programmatically

Tags:

c#

anglesharp

All AngleSharp examples and tests I found start with parsing a CSS or HTML snippet and access the DOM reading. How can I build a CSS (or HTML5) document programmatically and get the resulting output as string?

I want something like this (pseudo code):

var rule = new CssRule();
rule.Selector = ".my-class";

var style = new CssStyle("margin-top", "10px");

rule.add(style);
like image 936
gpinkas Avatar asked Jul 21 '26 01:07

gpinkas


1 Answers

For HTML you need to use the W3C specified API:

var context = BrowsingContext.New();
// get new document, not completely empty (has head and body)
var document = await context.OpenNewAsync();
var element = document.CreateElement("strong");
element.TextContent = "Hello World!";
document.Body.AppendChild(element);

As this is a little verbose some helpers (in form of extension methods) exist to make it more fluent. Also the CreateElement is available as a generic method looking like:

var paragraph = document.CreateElement<IHtmlParagraphElement>();

Unfortunately, for CSS currently no such API (factory methods or similar) exist. The only way to manipulate it is by using strings. This is not ideal (I know) and I will add useful extension methods to provide such functionality in the future.

like image 128
Florian Rappl Avatar answered Jul 22 '26 15:07

Florian Rappl