gpt4 book ai didi

c# - 你能控制 TagBuilder 类呈现属性的顺序吗?

转载 作者:太空狗 更新时间:2023-10-29 23:26:54 27 4
gpt4 key购买 nike

我知道这有点强制症,但是有没有一种方法可以控制 TagBuilder 类在您调用 ToString() 时呈现 HTML 标记属性的顺序>?

即这样

var tb = new TagBuilder("meta");            
tb.Attributes.Add("http-equiv", "Content-Type");
tb.Attributes.Add("content", "text/html; charset=utf-8");
tb.ToString(TagRenderMode.SelfClosing)

会回来

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

不是

<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />

更改添加属性的顺序不会改变它,它似乎是按字母顺序呈现的

最佳答案

尝试使用此类,它继承了 TagBuilder 并覆盖了 ToString 方法,从属性构建 SortedDictionary 并使用该字典进行渲染。

    public class MyTagBuilder : TagBuilder
{
//required to inherit from TagBuilder
public MyTagBuilder(string tagName) : base(tagName){}

//new hides the original ToString(TagRenderMode renderMode)
//The only changes in this method is that all calls to GetAttributesString
//have been changed to GetMyAttributesString
public new string ToString(TagRenderMode renderMode)
{
switch (renderMode)
{
case TagRenderMode.StartTag:
return string.Format(CultureInfo.InvariantCulture, "<{0}{1}>", new object[] { this.TagName, this.GetMyAttributesString() });

case TagRenderMode.EndTag:
return string.Format(CultureInfo.InvariantCulture, "</{0}>", new object[] { this.TagName });

case TagRenderMode.SelfClosing:
return string.Format(CultureInfo.InvariantCulture, "<{0}{1} />", new object[] { this.TagName, this.GetMyAttributesString() });
}
return string.Format(CultureInfo.InvariantCulture, "<{0}{1}>{2}</{0}>", new object[] { this.TagName, this.GetMyAttributesString(), this.InnerHtml });
}

//Implement GetMyAttributesString where the Attributes are changed to a SortedDictionary
private string GetMyAttributesString()
{
var builder = new StringBuilder();
var myDictionary = new SortedDictionary<string, string>(); //new
foreach (KeyValuePair<string, string> pair in this.Attributes) //new
{ //new
myDictionary.Add(pair.Key, pair.Value); //new
} //new
//foreach (KeyValuePair<string, string> pair in this.Attributes)
foreach (KeyValuePair<string, string> pair in myDictionary) //changed
{
string key = pair.Key;
if (!string.Equals(key, "id", StringComparison.Ordinal) || !string.IsNullOrEmpty(pair.Value))
{
string str2 = HttpUtility.HtmlAttributeEncode(pair.Value);
builder.AppendFormat(CultureInfo.InvariantCulture, " {0}=\"{1}\"", new object[] { key, str2 });
}
}
return builder.ToString();
}
}

关于c# - 你能控制 TagBuilder 类呈现属性的顺序吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3465460/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com