사용법 :
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" />
소스를 보면, 당신은 당신이 몇 가지 물건을 작업 할 수있다 2 곳 등을 달성하는 것을 발견 할 것이다 맡은 일.
readonly NodeFlags Node._flags
:이 필드, 속성 및 호스트 클래스는 모두 공개되지 않습니다. 그래서 당신은 직업을 얻으려면 더러운 해킹이 필요합니다. 또한 기본 서식 지정자 HtmlMarkupFormatter
은 >
만 사용하고 />
은 사용하지 않습니다.
- 나만의
IMarkupFormatter
을 만듭니다. 여기
두 지점을 언급 사용하는 솔루션이다.
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();
}
}
또한 ElementExtensions
를 제거하고 CustomHtmlMarkupFormatter.OpenTag
에서 자기 주변 요소에 때를 위해 자신의 논리를 추가 할 수 있습니다.