C# 如何使用AngleSharp制作自动关闭标签
对于这个特定的示例,我正在处理C# 如何使用AngleSharp制作自动关闭标签,c#,anglesharp,C#,Anglesharp,对于这个特定的示例,我正在处理input标记,做一些工作并用自定义标记替换它们。 输出为。 是否可以使用AngleSharp“生产”自动关闭标签 <customTag attr="x" /> 用法: var document = new HtmlParser().Parse(""); var tag = document.CreateElement("customTag"); tag.SetAttribute("attr", "x"); tag.AsSelfClosing()
input
标记,做一些工作并用自定义标记替换它们。
输出为。
是否可以使用AngleSharp“生产”自动关闭标签
<customTag attr="x" />
用法:
var document = new HtmlParser().Parse("");
var tag = document.CreateElement("customTag");
tag.SetAttribute("attr", "x");
tag.AsSelfClosing();
Console.WriteLine(tag.OuterHtml);
tag.ToHtml(Console.Out, CustomHtmlMarkupFormatter.Instance);
输出:
<customtag attr="x">
<customtag attr="x" />
您还可以删除ElementExtensions
,并在CustomHtmlMarkupFormatter.OpenTag
中添加自己的逻辑,以确定何时自动关闭元素
<customtag attr="x">
<customtag attr="x" />
public static class ElementExtensions
{
public static void AsSelfClosing(this IElement element)
{
const int SelfClosing = 0x1;
var type = typeof(IElement).Assembly.GetType("AngleSharp.Dom.Node");
var field = type.GetField("_flags", BindingFlags.Instance | BindingFlags.NonPublic);
var flags = (uint)field.GetValue(element);
flags |= SelfClosing;
field.SetValue(element, Enum.ToObject(field.FieldType, flags));
}
}
public class CustomHtmlMarkupFormatter : IMarkupFormatter
{
public static readonly CustomHtmlMarkupFormatter Instance = new CustomHtmlMarkupFormatter();
public string Text(String text) => HtmlMarkupFormatter.Instance.Text(text);
public string Comment(IComment comment) => HtmlMarkupFormatter.Instance.Comment(comment);
public string Processing(IProcessingInstruction processing) => HtmlMarkupFormatter.Instance.Processing(processing);
public string Doctype(IDocumentType doctype) => HtmlMarkupFormatter.Instance.Doctype(doctype);
//public string OpenTag(IElement element, Boolean selfClosing) => HtmlMarkupFormatter.Instance.OpenTag(element, selfClosing);
public string CloseTag(IElement element, Boolean selfClosing) => HtmlMarkupFormatter.Instance.CloseTag(element, selfClosing);
public string Attribute(IAttr attribute) => HtmlMarkupFormatter.Instance.Attribute(attribute);
public string OpenTag(IElement element, Boolean selfClosing)
{
var temp = new StringBuilder();
temp.Append('<');
if (!String.IsNullOrEmpty(element.Prefix))
{
temp.Append(element.Prefix).Append(':');
}
temp.Append(element.LocalName);
foreach (var attribute in element.Attributes)
{
temp.Append(" ").Append(Instance.Attribute(attribute));
}
temp.Append(selfClosing ? " />" : ">");
return temp.ToString();
}
}