使用AngleSharp库可以将HTML属性转换为字典。以下是一个示例代码:
using AngleSharp.Dom;
using AngleSharp.Html.Dom;
using System;
using System.Collections.Generic;
public class Program
{
public static void Main(string[] args)
{
string html = "Hello World";
var parser = new AngleSharp.Html.Parser.HtmlParser();
IHtmlDocument document = parser.ParseDocument(html);
IElement divElement = document.QuerySelector("div");
IDictionary attributes = GetAttributes(divElement);
foreach (var attribute in attributes)
{
Console.WriteLine($"Attribute: {attribute.Key}, Value: {attribute.Value}");
}
}
public static IDictionary GetAttributes(IElement element)
{
var attributes = new Dictionary();
foreach (var attribute in element.Attributes)
{
attributes.Add(attribute.Name, attribute.Value);
}
return attributes;
}
}
在上面的示例中,我们首先使用AngleSharp的HTML解析器将HTML字符串解析为IHtmlDocument对象。然后,使用QuerySelector方法选择要获取属性的元素(在这里是
运行上述代码将输出:
Attribute: id, Value: myDiv
Attribute: class, Value: myClass
Attribute: data-custom, Value: 123