Search code examples
c#anglesharp

How to build AngleSharp CSS (or HTML) DOM programmatically


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);

Solution

  • 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.