如何以编程方式构建AngleSharp CSS(或HTML)DOM

gpi*_*kas 2 c# anglesharp

我发现的所有AngleSharp示例和测试都始于解析CSS或HTML代码段并访问DOM。如何以编程方式构建CSS(或HTML5)文档,并以字符串形式获取结果输出?

我想要这样的东西(伪代码):

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

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

rule.add(style);
Run Code Online (Sandbox Code Playgroud)

Flo*_*ppl 5

对于HTML,您需要使用W3C指定的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);
Run Code Online (Sandbox Code Playgroud)

由于这有点冗长,因此存在一些帮助程序(以扩展方法的形式)以使其更加流畅。还CreateElement可以将用作通用方法,如下所示:

var paragraph = document.CreateElement<IHtmlParagraphElement>();
Run Code Online (Sandbox Code Playgroud)

不幸的是,对于CSS,目前尚不存在此类API(工厂方法或类似方法)。操纵它的唯一方法是使用字符串。这不是理想的(我知道),将来我会添加有用的扩展方法来提供此类功能。